695. Max Area of Island最大岛屿面积

Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)

Example 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]]

Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.

Example 2:

[[0,0,0,0,0,0,0,0]]

Given the above grid, return 0.

 

思路:

里面:加起来,得出一个和

外面:比较,双重for循环和所有点的和比较

 

没想到的主要思路是:加一个1就消灭一个,记为0,各个击破。这是为了避免重复计算

 

不是1的情况返回0

 

if (grid[x][y] == 1)直接变成&,不需要嵌套

 

class Solution {
    public int maxAreaOfIsland(int[][] grid) {
        //cc
        if (grid.length == 0 || grid[0].length == 0) {
            return 0;
        }
        
        int max = 0;
        
        //每一个点逐一比较
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                max = Math.max(max, dfs(grid, i, j));
            }
        }
        
        return max;
    }
    
    //返回面积
    public int dfs(int[][] grid, int x, int y) {
        //标记
        if (x >= 0 && x < grid.length && y >= 0 && y < grid[0].length && 
           grid[x][y] == 1) {             
                grid[x][y] = 0;
                
                return 1 + dfs(grid, x - 1, y) + dfs(grid, x + 1, y) + 
                    dfs(grid, x, y - 1) + dfs(grid, x, y + 1);          
        }
        
        return 0;
    }
}
View Code

 

posted @ 2020-08-26 23:15  苗妙苗  阅读(157)  评论(0编辑  收藏  举报