一、问题描述
二、解决方案
遍历整个二维表,当发现二维表中某个节点的值为1时,开始感染,执行 infect(int[][] m, int i, int j, int N, int M),i,j表示坐标,N,M表示二维表的边界排除掉不满足条件的节点,再次递归,直到感染了所有相邻的节点,此时感染掉的节点数值置为2,所以infect被触发了几次就说明有几个“岛”
三、实现
public class Problem_02_Islands {
public static int countIslands(int[][] m) {
if (m == null || m[0] == null) {
return 0;
}
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++;
//只要发现数值是1立刻进行感染
//所以发现几次1就说明感染了几次
infect(m, i, j, N, M);
}
}
}
return res;
}
public static void infect(int[][] m, int i, int j, int N, int M) {
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);
//向上下左右四个方向感染
}
public static void main(String[] args) {
// int[][] m1 = { { 0, 0, 0, 0, 0, 0, 0, 0, 0 },
// { 0, 1, 1, 1, 0, 1, 1, 1, 0 },
// { 0, 1, 1, 1, 0, 0, 0, 1, 0 },
// { 0, 1, 1, 0, 0, 0, 0, 0, 0 },
// { 0, 0, 0, 0, 0, 1, 1, 0, 0 },
// { 0, 0, 0, 0, 1, 1, 1, 0, 0 },
// { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, };
// System.out.println(countIslands(m1));
int[][] m2 = { { 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 1, 1, 1, 1, 1, 1, 1, 0 },
{ 0, 1, 1, 1, 0, 0, 0, 1, 0 },
{ 0, 1, 1, 0, 0, 0, 1, 1, 0 },
{ 0, 0, 0, 0, 0, 1, 1, 0, 0 },
{ 0, 0, 0, 0, 1, 1, 1, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 1 }, };
System.out.println(countIslands(m2));
}
}