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:
int numIslands(vector<vector<char> >& grid) {
int m, n, res = 0;
if((m = grid.size()) == 0 || (n = grid[0].size()) == 0) return res;
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++){
if(grid[i][j] == '1'){
res++;
dfs(grid, i, j);
}
} return res;
}
private:
int col[4] = {0, 0, -1, 1};
int row[4] = {1, -1, 0, 0};
void dfs(vector<vector<char> >& grid, int i, int j){
grid[i][j] = '2';
for(int k = 0; k < 4; k++){
int newI = i + row[k];
int newJ = j + col[k];
if(0 <= newI && newI < grid.size()
&& 0 <= newJ && newJ < grid[0].size()
&& grid[newI][newJ] == '1')
dfs(grid, newI, newJ);
}
}
};