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
Difficulty:Medium
DFS
class Solution {
public:
vector<vector<int>> visited;
//vector<vector<int>> nums;
void findIsland(vector<vector<char>>& grid,int i, int j){
int row = grid.size();
int col = grid[0].size();
visited[i][j] = 1;
if(i+1>=0&&i+1<row&&j>=0&&j<col&&grid[i+1][j]=='1'&&visited[i+1][j]==0){
findIsland(grid,i+1,j);
}
if(i-1>=0&&i-1<row&&j>=0&&j<col&&grid[i-1][j]=='1'&&visited[i-1][j]==0){
findIsland(grid,i-1,j);
}
if(i>=0&&i<row&&j+1>=0&&j+1<col&&grid[i][j+1]=='1'&&visited[i][j+1]==0){
findIsland(grid,i,j+1);
}
if(i>=0&&i<row&&j-1>=0&&j-1<col&&grid[i][j-1]=='1'&&visited[i][j-1]==0){
findIsland(grid,i,j-1);
}
}
int numIslands(vector<vector<char>>& grid) {
int row = grid.size();
if(row==0)
return 0;
int col = grid[0].size();
vector<int> temp(col,0);
for(int i = 0;i<row;i++){
visited.push_back(temp);
}
int count = 0;
for(int i =0;i < row;i++)
for(int j = 0; j < col; j++)
{
if(visited[i][j]!=0||grid[i][j]=='0')
;
else{
findIsland(grid,i,j);
count++;
}
}
return count;
}
};