Leetcode 695 岛屿的最大面积 二维平面DFS

  JAVA DFS:

public final int maxAreaOfIslandDFS(int[][] grid) {
        int re = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                re = Math.max(re, dfs(grid, i, j));
            }
        }
        return re;
    }

    private final int dfs(int[][] grid, int x, int y) {
        if (x < 0 || y < 0 || x >= grid.length || y >= grid[0].length || grid[x][y] == 0) return 0;
        grid[x][y] = 0;
        return dfs(grid, x - 1, y) + dfs(grid, x + 1, y) + dfs(grid, x, y - 1) + dfs(grid, x, y + 1) + 1;
    }

  JS DFS:

/**
 * @param {number[][]} grid
 * @return {number}
 */
var maxAreaOfIsland = function (grid) {
    let re = 0;
    for (let i = 0; i < grid.length; i++) {
        for (let j = 0; j < grid[0].length; j++) {
            re = Math.max(re, dfs(grid, i, j));
        }
    }
    return re;
};

var dfs = (grid, x, y) => {
    if (x < 0 || y < 0 || x >= grid.length || y >= grid[0].length || grid[x][y] == 0) return 0;
    grid[x][y] = 0;
    return dfs(grid, x + 1, y) + dfs(grid, x - 1, y) + dfs(grid, x, y + 1) + dfs(grid, x, y - 1) + 1;
}

 

posted @ 2020-12-01 20:20  牛有肉  阅读(143)  评论(0编辑  收藏  举报