publicintnumIslands(char[][] m){ if (m == null || m.length == 0) { return0; } int N = m.length; int M = m[0].length; int res = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (m[i][j] == '1') { res++; infect(m, i, j, N, M); } } } return res; }
publicstaticvoidinfect(char[][] m, int i, int j, int N, int M){ //只当一个位置为1时才进行感染过程 if (i < 0 || i >= N || j < 0 || j >= M || m[i][j] != '1') { return; } m[i][j] = '2'; infect(m, i + 1, j, N, M); infect(m, i - 1, j, N, M); infect(m, i, j + 1, N, M); infect(m, i, j - 1, N, M); }