岛问题

一个矩阵中只有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
这个矩阵中有三个岛。


思路:1,从头到尾遍历,如果发现此位置等于1,则进入感染状态。
2,感染状态:利用递归,把附近为1的全部标记为2。
3,重复1步骤。
public class IsLand {
public static int countIsland(int [][] arr){
//记得判断一下是否为null
if(arr==null||arr[0]==null){
return 0;
}
int N = arr.length; //长度
int M = arr[0].length; //宽度
int res = 0;
for (int i=0;i<N;i++){
for (int j =0;j<M;j++){
if(arr[i][j]==1){
infect(arr,i,j,N,M);
res++;
}
}
}
return res;
}
//设置感染,当为1时,感染四周的为2,因为四周都要看,所以要i,j都判断是否小于0
public static void infect(int arr[][],int i,int j,int N,int M){
if(i<0||i>=N||j<0||j>=M||arr[i][j]!=1){ //限定条件
return;
}
arr[i][j] = 2;
infect(arr,i+1,j,N,M); //下面这4个语句代表了向四周扩散。
infect(arr,i-1,j,N,M);
infect(arr,i,j+1,N,M);
infect(arr,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(countIsland(m2));
}
}
总结:看似很难,但是仔细分析之后发现,利用递归解,比较简单。

原文地址:https://www.cnblogs.com/liuwentao/p/9352838.html