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:
Input: grid = [ ["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","0"] ] Output: 1
Example 2:
Input: grid = [ ["1","1","0","0","0"], ["1","1","0","0","0"], ["0","0","1","0","0"], ["0","0","0","1","1"] ] Output: 3Number of Islands
class Solution {
public:
bool dfs(vector<vector<char> > &v,int i,int j,int n,int m)
{
if(i<0||j<0||j>=m||i>=n||v[i][j]=='0'||v[i][j]=='2')
return false;
v[i][j]='2';
dfs(v,i,j-1,n,m);
dfs(v,i,j+1,n,m);
dfs(v,i-1,j,n,m);
dfs(v,i+1,j,n,m);
return true;
}
int numIslands(vector<vector<char>>& grid) {
int ans=0;
for(int i=0;i<grid.size();++i)
{
for(int j=0;j<grid[i].size();++j)
{
if(grid[i][j]=='1')
{
if(dfs(grid,i, j, grid.size(),grid[0].size()))
++ans;
}
}
}
return ans;
}
};