Find the largest area of the island

Today’s topic is to find the largest area of ​​the island, let’s look at the topic requirements.

给定一个包含了一些 0  1 的非空二维数组 grid 
    一个 岛屿 是由一些相邻的 1 (代表土地) 构成的组合,这里的「相邻」要求两个 1 
    必须在水平或者竖直方向上相邻。你可以假设 grid 的四个边缘都被 0(代表水包围着。
    找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为 0 )

    示例 1:
    [[0,0,1,0,0,0,0,1,0,0,0,0,0],
     [0,0,0,0,0,0,0,1,1,1,0,0,0],
     [0,1,1,0,1,0,0,0,0,0,0,0,0],
     [0,1,0,0,1,1,0,0,1,0,1,0,0],
     [0,1,0,0,1,1,0,0,1,1,1,0,0],
     [0,0,0,0,0,0,0,0,0,0,1,0,0],
     [0,0,0,0,0,0,0,1,1,1,0,0,0],
     [0,0,0,0,0,0,0,1,1,0,0,0,0]]
    对于上面这个给定矩阵应返回 6。注意答案不应该是 11 ,因为岛屿只能包含水平或垂
    直的四个方向的 1 

    示例 2:
    [[0,0,0,0,0,0,0,0]]
    对于上面这个给定的矩阵, 返回 0

First of all, according to the requirements of the question, find the maximum continuous number of 1s that meet the conditions in the two-dimensional array. We can quickly determine that such a question is the most suitable to be solved by depth-first search. The
old rule is to find the three elements of recursion.

One, function design

遇到这种需要在二维数组中查找符合条件的因素的,直接传入 **行和列**
public void dfs(int i , int j)

2. Termination conditions

当跳出这个二维数组后终止,因为加了个染色条件,还需要多个判断
在这里插入代码片
if (i<0 || j<0 || i>=row || j>=col || input[i][j] == 0) 

Three, recursion direction

这种类型的提议,判断需要移动,就直接上下左右,四个方向啦!
        dfs(i+1,j);
        dfs(i-1,j);
        dfs(i,j+1);
        dfs(i,j-1);

Paste code

在这里插入代码片
public static int getMaxArea(int[][] grids) {
    
    
        if (grids.length == 0) return 0 ;
        input = grids ;
        row = grids.length ;
        col = grids[0].length ;
        for (int i = 0; i < row; i++) {
    
    
            for (int j = 0; j < col; j++) {
    
    
                if (input[i][j] == 1) {
    
    
                    dfs(i, j);
                    count = 0;
                }
            }
        }
        return res ;
    }
   static int row , col ;
    static int count , res ;
    static int[][] input ;
    public static void dfs(int i , int j) {
    
    
        if (i<0 || j<0 || i>=row || j>=col || input[i][j] == 0) {
    
    
            res = Math.max(res,count) ;
            return;
        }
        count++ ;
        input[i][j] = 0 ;
        dfs(i+1,j);
        dfs(i-1,j);
        dfs(i,j+1);
        dfs(i,j-1);
    }

Finished, let’s test it out
Insert picture description here
!
November 22, 2020 20:48:34

Guess you like

Origin blog.csdn.net/weixin_45302751/article/details/109963373