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.
Note: The length of each dimension in the given grid does not exceed 50.

应该说是基础的DFS题,但是巨久没有写搜索了,感觉完全不会BFS和DFS了。做完了contest第二天看了下答案,发现跟Number of islands这种题完全就是一样的套路,感觉最近必须得回归基础了。别去搞什么太fancy的东西,讲真那些高大上的项目写在简历上,真有那个水平早就在工业界拿高薪了,怎么可能还在找实习。回归算法和数据结构的基础,做好基础题,熟悉基础套路,我觉得完全够了。

这道题用的是DFS, 具体为灌水法。我们用两个for循环搜索grid, 每次遇到0就continue; 遇到1就进行DFS, 然后更新当前的maxArea. DFS返回的是当前grid[i][j]所在岛屿的最大面积。我们先判断该点是否在规定范围内,然后将grid[i][j] == 1的点先标为0,就好像是吃掉了这个岛。同时,我们也要对这个点周围四个方向的点进行DFS搜索,将所有链接起来的岛标为0,形象地比喻就好像灌水一样,一口吃掉所有连接的岛。我们返回的时候,要返回上下左右所有DFS的值之和加上1. 如果grid[i][j] == 0,则DFS method直接返回0.

class Solution {
    public int n;
    public int m;
    public int maxAreaOfIsland(int[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0){
            return 0;
        }
        n = grid.length;
        m = grid[0].length;
        int maxArea = 0;
        for (int i = 0; i < n; i++){
            for (int j = 0; j < m; j++){
                if (grid[i][j] == 0){
                    continue;
                } else {
                    maxArea = Math.max(maxArea, dfsHelper(grid,i,j));
                }
            }
        }
        return maxArea;
    }
    
    private int dfsHelper(int[][] grid, int i, int j){
        if (i < 0 || i >= n || j < 0 || j >= m || grid[i][j] == 0){
            return 0;
        }
        if (grid[i][j] == 1){
            grid[i][j] = 0;
            return 1 + dfsHelper(grid,i, j - 1) + dfsHelper(grid,i - 1, j) +  dfsHelper(grid,i, j + 1) + dfsHelper(grid,i + 1, j);
        }
        return 0;
    }
}

推荐阅读更多精彩内容