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 cnt = 0;
if (!grid.size())
return 0;
if (!grid[0].size())
return 0;
vector<vector<bool>> marks(grid.size());
for (int i = 0; i < grid.size(); i++){
marks[i].resize(grid[0].size());
}
for (int i = 0; i < grid.size(); i++){
for (int j = 0; j < grid[0].size(); j++){
if (grid[i][j] == '1' && marks[i][j] == 0){
cnt++;
islandMark(marks, grid, i, j);
}
}
}
return cnt;
}
void islandMark(vector<vector<bool>>& marks, vector<vector<char>>& grid, int i, int j){
if (0 <= i && i < grid.size() && 0 <= j&&j < grid[0].size() && marks[i][j] == 1)
return;
if (0<=i && i<grid.size() && 0<=j&&j<grid[0].size() && grid[i][j] == '1'){
marks[i][j] = 1;
islandMark(marks, grid, i, j + 1);
islandMark(marks, grid, i + 1, j);
islandMark(marks, grid, i-1, j);
islandMark(marks, grid, i, j-1);
}
else
return;
}
};