示例 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
};