查找最大的小岛面积

问题
Given an NxN matrix of 0's and 1's; 0's representing water, and 1's representing land. Find the largest landmass in the area that includes the lakes encompassed by the landmass.

You can safely assume the following:

  1. The grid is a square (as indicated above.)
  2. All four corners are guaranteed to be open ocean, and will collectively connect to all ocean in the input.
  3. Land is connected in 4 directions (up, down, left, right)
  4. You do not need to preserve the state of the input

0 0 0 0 0 0
0 0 1 1 1 0
0 1 0 0 1 0
0 1 0 0 1 0
0 1 0 0 1 0
0 0 1 1 0 0

答案: 17

代码

    /**
     * @Date 2022/03/26 14:29
     * @Comment 水域部分分为外水(连接边界的大水域)和内水(小池塘),将外水排除掉,剩余内水就知道了,将内水全部换为陆地,查找陆地面积
    */
    public int findMaxLand(int[][] matrixs){
        int len = matrixs[0].length;
        //查找外水 将外水置为-1
        for(int i=0;i<len;i++){
            for(int j=0;j<len;j++){
                if((i==0||j==0||i==len-1||j==len-1)&&matrixs[i][j]==0){
                    dfs1(matrixs,len,i,j);
                }
            }
        }
        //查找陆地面积 剩余的0和1即陆地
        int ans = 0;
        for(int i=0;i<len;i++){
            for(int j=0;j<len;j++){
                if(matrixs[i][j]>=0){
                    ans = Math.max(dfs2(matrixs,len,i,j),ans);
                }
            }
        }
        return ans;
    }
    public void dfs1(int[][] matrixs,int len,int i,int j){
        if(i<0||i>=len||j<0||j>=len||matrixs[i][j]!=0){
            return;
        }
        matrixs[i][j]=-1;
        dfs1(matrixs,len,i-1,j);
        dfs1(matrixs,len,i,j+1);
        dfs1(matrixs,len,i,j-1);
        dfs1(matrixs,len,i+1,j);
    }
    public int dfs2(int[][] matrixs,int len,int i,int j){
        if(i<0||i>=len||j<0||j>=len||matrixs[i][j]<0){
            return 0;
        }
        matrixs[i][j]=-1;
        return 1+dfs2(matrixs,len,i-1,j)+dfs2(matrixs,len,i,j+1)+dfs2(matrixs,len,i,j-1)+dfs2(matrixs,len,i+1,j);
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        LandUtils landUtils = new LandUtils();

        int[][] matrixs = new int[6][6];
        matrixs[0] = new int[]{0,0,0,0,0,0};
        matrixs[1] = new int[]{0,0,1,1,1,0};
        matrixs[2] = new int[]{0,1,0,0,1,0};
        matrixs[3] = new int[]{0,1,0,0,1,0};
        matrixs[4] = new int[]{0,1,0,0,1,0};
        matrixs[5] = new int[]{0,0,1,1,0,0};
        int res = landUtils.findMaxLand(matrixs);
        System.out.println(res);
    }
}```
posted @ 2022-03-26 14:59  tongyongliang  阅读(33)  评论(0编辑  收藏  举报