给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。
示例 1:
输入:
11110
11010
11000
00000
输出: 1
示例 2:
输入:
11000
11000
00100
00011
输出: 3
class Solution {
public:
int dist[][] = {,,,-,,,-,};
queue<pair<int,int>>que;
void dfs(vector<vector<char>>& grid,vector<vector<int>>& sign,int i,int j,int row,int col,int num){
sign[i][j] = ;
int ii,jj;
for(int zz = ;zz < ;zz++){
ii = i + dist[zz][];
jj = j + dist[zz][];
if(ii < ||jj < ||ii >= row||jj >= col) continue;
if(sign[ii][jj] == ) continue;
if(grid[ii][jj] == '')
dfs(grid,sign,ii,jj,row,col,num);
}
}
void bfs(vector<vector<char>>& grid,vector<vector<int>>& sign,int i,int j,int row,int col,int num){
sign[i][j] = ;
int ii,jj;
for(int zz = ;zz < ;zz++){
ii = i + dist[zz][];
jj = j + dist[zz][];
if(ii < ||jj < ||ii >= row||jj >= col) continue;
if(sign[ii][jj] == ) continue;
if(grid[ii][jj] == ''){
sign[ii][jj] = ;
que.push({ii,jj});
}
}
while(!que.empty()){
ii = que.front().first;
jj = que.front().second;
que.pop();
bfs(grid,sign,ii,jj,row,col,num);
} }
int numIslands(vector<vector<char>>& grid) {
if(grid.size() == ||grid[].size() == )
return ;
int row = grid.size();
int col = grid[].size();
int num = ;
vector<vector<int>>sign(row,vector<int>(col,));
for(int i = ;i < row;i++){
for(int j = ;j < col;j++){
if(sign[i][j] == && grid[i][j] == ''){
num++;
dfs(grid,sign,i,j,row,col,num);
}
}
}
return num;
}
};