Given a 2d grid map of '1'
s (land) and '0'
s (water), count 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.
Example 1:
11110 11010 11000 00000
Answer: 1
Example 2:
11000 11000 00100 00011
Answer: 3
class Solution {
public:
/*algorithm: BFS
1)if grid[i][j] is '1', count++,BFS search from (i,j),mark them to '#'
2)scan grid row by row
time O(m*n), space O(1)
*/
void bfs(vector<vector<char>>& grid,int x,int y,int m,int n){
if(x < 0 || x >= m ||y < 0 || y >= n)return;
if(grid[x][y] == '1'){
grid[x][y] = '#';
bfs(grid,x-1,y,m,n);//top
bfs(grid,x,y+1,m,n);//right
bfs(grid,x+1,y,m,n);//down
bfs(grid,x,y-1,m,n);//left
}
}
int numIslands(vector<vector<char>>& grid) {
int m = grid.size();
if(m < 1)return 0;
int n = grid[0].size();
if(n < 1)return 0;
int cnt = 0;
for(int r = 0;r < m;r++){
for(int c = 0;c < n;c++){
if(grid[r][c] == '1'){
++cnt;
bfs(grid,r,c,m,n);
}
}
}
return cnt;
}
};