LeetCode 200 Number of Islands
Given an m x n
2D binary grid grid which represents a map of '1
's (land) and '0
's (water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Solution
求连通块个数,直接 \(BFS\) 就可以
点击查看代码
class Solution {
private:
int ans=0;
int vis[301][301];
int dir[4][2] = {0,1, 1,0, 0,-1, -1,0};
bool check(int i, int j, int r, int c){
if(i<0||j<0||i>=r||j>=c) return false;
return true;
}
void dfs(int x,int y,int r,int c, vector<vector<char>>& grid){
if(vis[x][y])return;
vis[x][y] = 1;
for(int i=0;i<4;i++){
int nx = x+dir[i][0], ny = y+dir[i][1];
if(check(nx,ny,r,c)&& grid[nx][ny]=='1')dfs(nx,ny,r,c, grid);
}
}
public:
int numIslands(vector<vector<char>>& grid) {
int r = grid.size(), c = grid[0].size();
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
if(!vis[i][j]&&grid[i][j]=='1'){ans++; dfs(i,j,r,c, grid);}
}
}
return ans;
}
};