给定一个由 ‘1’(陆地)和 ‘0’(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。
示例 1:
输入:
11110
11010
11000
00000
输出: 1
示例 2:
输入:
11000
11000
00100
00011
输出: 3
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int hang= grid.size();
if(hang==0){
return 0;
}
int lie=grid[0].size();
queue<pair<int,int>> A;//用于存放坐标
int nums=0;
for(int i=0;i<hang;i++){
for(int j=0;j<lie;j++){
if(grid[i][j]=='1'){
cout<<i<<j<<endl;
nums++;
grid[i][j]=='0';
queue<pair<int, int>> B;//存储坐标i,j
B.push({i, j});
while(!B.empty()){
auto location = B.front();//取B得头节点指向坐标
B.pop();//将这个点删除
int h=location.first;//行
int l=location.second;//列
if(h-1>=0 && grid[h-1][l]=='1'){//上一行
B.push({h-1,l});//将此坐标加入到队列中
grid[h-1][l]='0';//此处修改为0
}
if(h+1<hang && grid[h+1][l]=='1'){//下一行
B.push({h+1,l});
grid[h+1][l]='0';
}
if(l-1>=0 && grid[h][l-1]=='1'){//左行
B.push({h,l-1});
grid[h][l-1]='0';
}
if(l+1<lie && grid[h][l+1]=='1'){//右一行
B.push({h,l+1});
grid[h][l+1]='0';
}
}
}
}
}
return nums;
}
};