小岛问题

问题描述:

一个只包含0和1的阵列,找到1的组的个数,每个组的定义是横向和纵向相邻的值都为1,如图中一共有4个组,用不同颜色的框分割(可以参见不同粗细勾画起来的框)。
package test;

public class 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++;
                    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, 0 }, };
        System.out.println(countIslands(m2));

    }
}
原文地址:https://www.cnblogs.com/xiaoxli/p/9560995.html