一、题目
给你一个由 '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
};
五、总结
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/weixin_47450807/article/details/123487935
内容来源于网络,如有侵权,请联系作者删除!