Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
找小岛的数量,如果一个1的上下左右有其他1,就和其他1组成一个小岛,否则自己是一个小岛。
使用深度优先加广度优先搜索算法。
首先遍历整个数组,找到第一个是1的位置。
顺着这个1使用深度优先搜索把和这个1一起组成小岛的位置都找出来,并全部标记为3,小岛数加1。
继续遍历数组,如果是0,是3都跳过,继续找1。
var numIslands = function(grid) {
var row = grid.length;
if (row === 0)
return 0;
var col = grid[0].length;
var count = 0;
for (let i = 0;i < row;i++) {
for (let j = 0;j < col;j++) {
//寻找新的小岛
if (grid[i][j]==='1') {
count++;
grid[i][j] = '3';
var stack = [[i,j]];
//找到属于这个岛的所有点并标记
while (stack.length!==0) {
var now = stack.pop();
var nowi = now[0];
var nowj = now[1];
if (nowi+1<row&&grid[nowi+1][nowj]==='1') {
grid[nowi+1][nowj] = '3';
stack.push([nowi+1,nowj]);
}
if (grid[nowi][nowj+1]==='1') {
grid[nowi][nowj+1] = '3';
stack.push([nowi,nowj+1]);
}
if (nowi-1>=0&&grid[nowi-1][nowj]==='1') {
grid[nowi-1][nowj] = '3';
stack.push([nowi-1,nowj]);
}
if (grid[nowi][nowj-1]==='1') {
grid[nowi][nowj-1] = '3';
stack.push([nowi,nowj-1]);
}
}
}
}
}
return count;
};
网友评论