Number of Islands(leetcode,cpp)

Number of Islands(leetcode,cpp)

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:
===========================================================================================
code:-
class Solution {
public:
int ROW,COL;
bool issafe(vector<vector<char >>& g,int r,int c)
{

if( r>=0 && c>=0 && r<ROW && c<COL)
{
if(g[r][c]=='1')
{

return true;
}
else
{
return false;
}



}
else
return false;
}


void dfs(vector<vector<char >>& g,int r,int c)
{

g[r][c]='2'; //visited

static int r_move[4]={0,-1,0,1};
static int c_move[4]={-1,0,1,0};

for(int i=0;i<4;i++)
{
if(issafe(g,r+r_move[i],c+c_move[i]) ) //not visited and safe
{



dfs(g,r+r_move[i],c+c_move[i]);

}

}
}

int numIslands(vector<vector<char >>& g)
{
int count=0;
if(g.size()==0)
return count;
ROW=g.size();

COL=g[0].size();



for(int i=0;i<g.size();i++)
{
for(int j=0;j<g[0].size();j++)
{

if(g[i][j]=='1')
{
count++;
// cout<<count<<endl;

dfs(g,i,j);
}
}
}
return count;


}

};

Comments

Popular posts from this blog

Amazing Subarrays(cpp,interviewbit)

Symmetric Tree(leetcode,cpp):

sum of left leaves in a tree(leetcode).