来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-islands
给定一个由 ‘1‘(陆地)和 ‘0‘(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。
示例 1:
输入:
11110
11010
11000
00000
输出: 1
示例 2:
输入:
11000
11000
00100
00011
输出: 3
深度优先搜索(DFS)
/**
* @param {character[][]} grid
* @return {number}
*/
var numIslands = function(grid) {
if(grid && grid[0]){
let x = grid.length;
let y = grid[0].length;
let num = 0;
for(let i=0; i<x; i++){
for(let j=0; j<y; j++){
if(grid[i][j] === ‘1‘){
num++;
count(i,j);
}
}
}
function count(i,j){
if(i<0 || i>x-1 || j<0 || j>y-1) return 0
if(grid[i][j] === ‘1‘){
grid[i][j] = 0;
count(i-1,j);
count(i,j-1);
count(i+1,j);
count(i,j+1);
}
}
return num;
}else{
return 0;
}
};
原文:https://www.cnblogs.com/liu-xin1995/p/12739987.html