200. 岛屿数量(js)

发布时间:2024年01月20日

示例 1:

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

示例 2:

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

思路:遍历网格,当前为1就是一个岛屿,然后以当前为中心,向左右上下扩散,把相邻的1置为0。

代码:

/**
 * @param {character[][]} grid
 * @return {number}
 */
var numIslands = function (grid) {
    let res = 0
    let zero = (y, x) => { // 置0
        let left = x - 1, right = x + 1, top = y - 1, bottom = y + 1
        while (grid[y][left] === '1') { // 左扩散
            grid[y][left] = '0'
            zero(y, left)
            left--
        }
        while (grid[y][right] === '1') { // 右扩散
            grid[y][right] = '0'
            zero(y, right)
            right++
        }
        while (top >= 0 && grid[top][x] === '1') { // 上扩散
            grid[top][x] = '0'
            zero(top, x)
            top--
        }
        while (bottom < grid.length && grid[bottom][x] === '1') { // 下扩散
            grid[bottom][x] = '0'
            zero(bottom, x)
            bottom++
        }
    }
    for (let y = 0; y < grid.length; y++) { // 找1
        for (let x = 0; x < grid[0].length; x++) {
            if (grid[y][x] === '1') {
                res++
                zero(y, x)
            }
        }
    }
    return res
};

文章来源:https://blog.csdn.net/qq_43119912/article/details/135714188
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。