岛屿数量
给你一个由’1’(陆地)和’0’(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
使用广度优先搜索方式进行搜索
思想:遍历所有的网格,遇到 1,我们就认为遇到了一个岛屿,然后对岛屿的其他范围进行搜索,通过广度优先,对相邻的每个元素进行遍历,如果遇到元素值为 1 的则加入队列。知道队列为空。
我们要将遍历过的值归零。这样所有的都为 0 即结束。
代码如下所示(C++):
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
// 获取数组的行数和列数
int rows = grid.size();
int cols = 0;
if(rows ==0){
return 0;
}else{
cols = grid[0].size();
}
int nums = 0; // 初始化岛屿数量
queue<pair<int,int>> Q;
// 遍历数组的每一个元素
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
if(grid[i][j] == '1'){ // 若当前元素值为1
nums++; // 岛屿数量加一
Q.push(make_pair(i,j));
grid[i][j] = '0'; // 将当前元素值设为0,表示已经访问
while(!Q.empty()){ // 循环迭代直到队列为空
pair<int,int> node = Q.front();
Q.pop();
int row = node.first, col = node.second;
// 遍历上下左右四格,若有元素值为1则加入队列
if(row + 1 < rows && grid[row+1][col] == '1'){
Q.push(make_pair(row+1,col));
grid[row+1][col] ='0';
}
if(col + 1 <cols && grid[row][col+1] == '1'){
Q.push(make_pair(row,col+1));
grid[row][col+1] ='0';
}
if(row - 1 >= 0 && grid[row-1][col] == '1'){
Q.push(make_pair(row-1,col));
grid[row-1][col] ='0';
}
if(col - 1 >= 0 && grid[row][col-1] == '1'){
Q.push(make_pair(row,col-1));
grid[row][col-1] ='0';
}
}
}
}
}
return nums;
}
};
放在最后
如果您喜欢我的文章,拜托点赞收藏关注,博主会根据大家喜好来推出相关系列文章~
更多精彩内容也可以访问我的博客Aelous-BLog