https://leetcode.com/problems/number-of-islands/description/
题目:求岛屿的数目,所有相连的1构成一个岛屿。
思路:BFS
class Solution {
public:
int sum = 0;
void BFS(vector<vector<char>>& grid,int x,int y){
int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
struct Q{
int x;
int y;
};
Q q[2500];
q[0].x = x;
q[0].y = y;
grid[x][y] = '0';
int l=0,r=1;
while(l<r){
Q temp = q[l];
for(int z=0;z<4;z++){
temp.x = q[l].x + dir[z][0];
temp.y = q[l].y + dir[z][1];
if(temp.x < 0 || temp.x >= grid.size() || temp.y < 0 || temp.y >= grid[0].size()
|| grid[temp.x][temp.y]=='0')
continue;
q[r] = temp;
grid[temp.x][temp.y] = '0';
r++;
}
l++;
}
sum++;
}
int numIslands(vector<vector<char>>& grid) {
for(int x=0;x<grid.size();x++)
for(int y=0;y<grid[0].size();y++)
if(grid[x][y] == '1')
BFS(grid,x,y);
return sum;
}
};