Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✅200. 岛屿数量 #40

Open
bazinga-web opened this issue Jun 26, 2020 · 2 comments
Open

✅200. 岛屿数量 #40

bazinga-web opened this issue Jun 26, 2020 · 2 comments
Labels
DFS 深度优先 中等

Comments

@bazinga-web
Copy link

200. 岛屿数量

给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。

岛屿总是被水包围,并且每座岛屿只能由水平方向或竖直方向上相邻的陆地连接形成。

此外,你可以假设该网格的四条边均被水包围。

示例 1:

输入:
11110
11010
11000
00000
输出: 1

示例 2:

输入:
11000
11000
00100
00011
输出: 3

解释: 每座岛屿只能由水平和/或竖直方向上相邻的陆地连接而成。

@bazinga-web
Copy link
Author

解题思路:

  1. 遍历二维数组,遇到“1”则让小岛数量加1
  2. 然后根据当前位置扩散,使用深度搜索的方式沉没小岛

bfs: (宽)广度优先搜索
dfs: 深度优先搜索

/**
 * @param {character[][]} grid
 * @return {number}
 */
var numIslands = function (grid) {
    let count = 0;
    function dfs(row, col) {
        if (
            row < 0 ||
            row >= grid.length ||
            col < 0 ||
            col >= grid[0].length ||
            grid[row][col] === "0"
        ) {
            return;
        }
        grid[row][col] = "0";
        dfs(row + 1, col);
        dfs(row - 1, col);
        dfs(row, col + 1);
        dfs(row, col - 1);
    }
    for (let row = 0; row < grid.length; row++) {
        for (let col = 0; col < grid[0].length; col++) {
            if (grid[row][col] === "1") {
                count++;
                dfs(row, col);
            }
        }
    }
    return count;
};

@Ray-56
Copy link
Owner

Ray-56 commented Jun 29, 2020

深度优先遍历

  • 遇到 1 岛屿数量加一的同时调用递归边界判断
function helper(grid, x, y, rowLen, colLen) {
    if (x < 0 || y < 0 || x > rowLen - 1 || y > colLen - 1 || grid[x][y] == '0') return;

    grid[x][y] = '0';

    helper(grid, x - 1, y, rowLen, colLen);
    helper(grid, x + 1, y, rowLen, colLen);
    helper(grid, x, y - 1, rowLen, colLen);
    helper(grid, x, y + 1, rowLen, colLen);
}
/**
 * @param {character[][]} grid
 * @return {number}
 */
var numIslands = function(grid) {
    // DFS
    let isLand = 0;
    const rowLen = grid.length;
    if (rowLen === 0) return 0;
    const colLen = grid[0].length;

    for (let x = 0; x < rowLen; x++) {
        for (let y = 0; y < colLen; y++) {
            if (grid[x][y] == '1') {
                helper(grid, x, y, rowLen, colLen);
                isLand++;
            }
        }
    }

    return isLand;
};

@Ray-56 Ray-56 added DFS 深度优先 中等 labels Jun 29, 2020
@Ray-56 Ray-56 changed the title 200. 岛屿数量 ✅200. 岛屿数量 Jun 29, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
DFS 深度优先 中等
Projects
None yet
Development

No branches or pull requests

2 participants