Bootstrap

LeetCode 695. 岛屿的最大面积

更多题解尽在 https://sugar.matrixlab.dev/algorithm 每日更新。
组队打卡,更多解法等你一起来参与哦!

LeetCode 695. 岛屿的最大面积,难度中等

DFS

解题思路:做过 200. 岛屿数量 的同学,做这题应该没有难度,两者解法相似。遍历二维数组,如果当前二维数组的元素是岛屿,则遍历其上下左右节点。

class Solution {
    public int maxAreaOfIsland(int[][] grid) {
        if (grid == null || grid.length == 0) return 0;
        int result = 0;
        int rows = grid.length;
        int cols = grid[0].length;

        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                if (grid[r][c] == 1) {
                    result = Math.max(result, dfs(grid, r, c));
                }
            }
        }
        return result;
    }

    private int dfs(int[][] grid, int r, int c) {
        int rows = grid.length;
        int cols = grid[0].length;

        if (r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] == 0) {
            return 0;
        }

        grid[r][c] = 0;
        return dfs(grid, r - 1, c) + dfs(grid, r + 1, c) + dfs(grid, r, c - 1) + dfs(grid, r, c + 1) + 1;
    }
}
;