class Solution {
private:
vector<vector<bool>> isCounted;
int d[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};//四方向移动
int r,c;
bool isLegal(int x,int y){
return 0<=x && x<r && 0<=y && y<c;
}
void dfs(vector<vector<char>>& grid,int i, int j){
isCounted[i][j] = true;
//cout<<i<<" "<<j<<endl;
for(int k=0;k<4;k++){
int newx = i + d[k][0];
int newy = j + d[k][1];
if(isLegal(newx,newy) && !isCounted[newx][newy] && grid[newx][newy] == '1'){
dfs(grid,newx,newy);
}
}
return;
}
public:
int numIslands(vector<vector<char>>& grid) {
int res = 0;//岛屿数量
r = grid.size();//行数
if(r == 0) return 0;
c = grid[0].size();//列数
isCounted = vector<vector<bool>>(r,vector<bool>(c,false));
for(int i = 0;i < r; i++){
for(int j = 0;j < c;j++){
if(!isCounted[i][j] && grid[i][j] == '1'){
//cout<<"a"<<endl;
//floodfill,用dfs将周围岛屿全部标记
dfs(grid,i,j);
res++;
}
}
}
return res;
}
};
【leetCode刷题日记】200. Number of Islands
最新推荐文章于 2024-11-05 21:58:11 发布