Skip to content

Latest commit

 

History

History
70 lines (49 loc) · 2.25 KB

695-max-area-of-island.md

File metadata and controls

70 lines (49 loc) · 2.25 KB

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

给定一个包含了一些 0 和 1的非空二维数组 grid , 一个 岛屿 是由四个方向 (水平或垂直) 的 1 (代表土地) 构成的组合。你可以假设二维矩阵的四个边缘都被水包围着。

找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为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

注意: 给定的矩阵grid 的长度和宽度都不超过 50。


题目标签:Depth-first Search / Array

题目链接:LeetCode / LeetCode中国

题解

Language Runtime Memory
java 31 ms 30.5 MB
class Solution {
    private int dfs(int[][] g, int x, int y) {
        if (x >= 0 && x < g.length && y >= 0 && y < g[0].length && g[x][y] == 1) {
            g[x][y] = -1;
            return 1 + dfs(g, x - 1, y) + dfs(g, x + 1, y) + dfs(g, x, y - 1) + dfs(g, x, y + 1);
        } else {
            return 0;
        }
    }

    public int maxAreaOfIsland(int[][] grid) {
        int res = 0;
        for (int x = 0; x < grid.length; x++) {
            for (int y = 0; y < grid[0].length; y++) {
                res = Math.max(res, dfs(grid, x, y));
            }
        }
        return res;
    }
}