一个矩阵中只有0和1两种值,每个位置都可以和自己的上、下、左、右 四个位置相连,如果有一片1连在一起,这个部分叫做一个岛,求一个 矩阵中有多少个岛?
举例:
0 0 1 0 1 0
1 1 1 0 1 0
1 0 0 1 0 0
0 0 0 0 0 0
这个矩阵中有三个岛
public class isLand {
public static int countIsLand(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++;
infact(m,i,j,N,M);
}
}
}
return res;
}
private static void infact(int[][] m, int i, int j, int N, int M) {
// TODO Auto-generated method stub
if(i>=N||j>=M||i<0|j<0||m[i][j]!=1) {
return ;
}
m[i][j]=2;
infact(m, i+1, j, N, M);
infact(m, i-1, j, N, M);
infact(m, i, j+1, N, M);
infact(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(countIsLand(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, 0 }, };
System.out.println(countIslands(m2));*/
}
}