Number of Islands
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 {
private:
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
void dfs(int x, int y,vector<vector<char> >& grid){
grid[x][y] = '0';
for(int m = 0; m < 4; m++){
int nx = x + dx[m];
int ny = y + dy[m];
if(nx >= 0 && nx < grid.size() && ny >= 0 && ny < grid[0].size() && grid[nx][ny] == '1'){
dfs(nx, ny, grid);
}
}
}
public:
int numIslands(vector<vector<char>>& grid) {
int count = 0;
for(int i = 0; i < grid.size(); i++){
for(int j = 0; j < grid[0].size(); j++){
if(grid[i][j] == '1'){
dfs(i, j, grid);
count++;
}
}
}
return count;
}
};