Leetcode刷题(第200题)——岛屿数量

x33g5p2x  于2022-03-14 转载在 其他  
字(1.2k)|赞(0)|评价(0)|浏览(323)

一、题目

给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。

二、示例

输入:grid = [
  ["1","1","1","1","0"],
  ["1","1","0","1","0"],
  ["1","1","0","0","0"],
  ["0","0","0","0","0"]
]
输出:1
输入:grid = [
  ["1","1","0","0","0"],
  ["1","1","0","0","0"],
  ["0","0","1","0","0"],
  ["0","0","0","1","1"]
]
输出:3

三、思路
本题应该遍历数组中的每一个元素,然后判断该元素是否为'1',如果为1则进行递归,如果不为1,则跳过。
四、代码展示

/**
 * @param {character[][]} grid
 * @return {number}
 */
var numIslands = function (grid) {
    const row = grid.length
    const col = grid[0].length
    let result = 0
    const rec = (x, y) => {
        if (x >= row || x < 0 || y >= col || y < 0 || grid[x][y] === '0') return
        grid[x][y] = '0'
            ;[[x, y + 1], [x, y - 1], [x - 1, y], [x + 1, y]].forEach(item => {
                rec(item[0], item[1])
            })
    }
    for (let i = 0; i < row; i++) {
        for (let j = 0; j < col; j++) {
            if (grid[i][j] === '1') {
                rec(i, j)
                result++
            }
        }
    }
    return result
};

五、总结

相关文章