leetcode 695. 岛屿的最大面积

给定一个包含了一些01的非空二维数组 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’

深度优先搜索

我们想知道网格中每个连通形状的面积,然后取最大值。
如果我们在一个土地上,以 4 个方向探索与之相连的每一个土地(以及与这些土地相连的土地),那么探索过的土地总数将是该连通形状的面积。
为了确保每个土地访问不超过一次,我们每次经过一块土地时,将这块土地的值置为 0。这样我们就不会多次访问同一土地。

class Solution {
    private int[][] grid;
    private int R;
    private int C;
    private int[][] dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
    private boolean[][] visited;

    public int maxAreaOfIsland(int[][] grid) {
        int res = 0;
        this.R = grid.length;
        this.C = grid[0].length;
        this.grid = grid;
        visited = new boolean[R][C];
        if (R == 0) return res;
        if (C == 0) return res;
        for (int i = 0; i < R; i++) {
            for (int j = 0; j < C; j++) {
                if (!visited[i][j] && grid[i][j] == 1)
                    res = Math.max(res,dfs(i, j));
            }
        }
        return res;
    }

    private int dfs(int x, int y) {
        int res = 1;
        grid[x][y] = 0;
        int nextx;
        int nexty;
        for (int d = 0; d < 4; d++) {
            nextx = x + dirs[d][0];
            nexty = y + dirs[d][1];
            if (inArea(nextx, nexty) && grid[nextx][nexty] == 1 && !visited[nextx][nexty]) {
                visited[nextx][nexty] = true;//标记这个位置已访问,避免下一次还会再访问这个位置
                grid[nextx][nexty] = 0; //访问过的就置为0
                res += dfs(nextx,nexty);
            }
        }
        return res;
    }

    private boolean inArea(int x, int y) {//检查是否再合法域中
        return x >= 0 && x < R && y >= 0 && y < C;
    }

    public static void main(String[] args) {
        int[][] gird = new int[][]{
                {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}
        };
        System.out.println(new Solution().maxAreaOfIsland(gird));
    }
}
原文地址:https://www.cnblogs.com/HoweZhan/p/12497876.html