题解 | #岛屿数量#
岛屿数量
http://www.nowcoder.com/practice/0c9664d1554e466aa107d899418e814e
/**
* 判断岛屿数量
* @param grid char字符型二维数组
* @return int整型
*/
//分享解题思路视频https://www.bilibili.com/video/BV1Y7411v7Wh/?spm_id_from=333.788.recommend_more_video.0
function solve( grid ) {
// write code here
function dfs(grid, i, j) {
if (i<0||i>=grid.length||j<0||j>=grid[0].length||grid[i][j] === '0') return
grid[i][j] = '0'
dfs(grid, i+1, j)
dfs(grid, i, j+1)
dfs(grid, i-1, j)
dfs(grid, i, j-1)
}
let count = 0
for(let i = 0; i<grid.length;i++){
for(let j = 0; j<grid[0].length;j++) {
if (grid[i][j] === '1') {
dfs(grid, i, j)
count++
}
}
}
return count
}
module.exports = {
solve : solve
};