Copy bool isValid ( int row , int col , int height , int width , vector < vector < bool >> & explored , vector < vector < char >> & ar)
{
return (row >= 0 && row < height && col >= 0 && col < width &&
explored [row][col] == 0 && ar [row][col] == '1' );
}
void dfs_cluster ( int row , int col , vector < vector < bool >> & explored ,
vector < vector < char >> & ar)
{
// up
if ( isValid (row - 1 , col , ar . size () , ar . at (row) . size () , explored , ar)) {
explored [row - 1 ][col] = 1 ;
dfs_cluster (row - 1 , col , explored , ar);
}
// down
if ( isValid (row + 1 , col , ar . size () , ar . at (row) . size () , explored , ar)) {
explored [row + 1 ][col] = 1 ;
dfs_cluster (row + 1 , col , explored , ar);
}
// right
if ( isValid (row , col + 1 , ar . size () , ar . at (row) . size () , explored , ar)) {
explored [row][col + 1 ] = 1 ;
dfs_cluster (row , col + 1 , explored , ar);
}
// left
if ( isValid (row , col - 1 , ar . size () , ar . at (row) . size () , explored , ar)) {
explored [row][col - 1 ] = 1 ;
dfs_cluster (row , col - 1 , explored , ar);
}
}
int numIslands ( vector < vector < char >> & ar)
{
int num_clusters = 0 ;
vector < vector <bool>> explored_ar ( ar . size () , vector < bool >( ar . at ( 0 ) . size ()));
for ( int i = 0 ; i < ar . size (); i ++ ) {
for ( int j = 0 ; j < ar . at (i) . size (); j ++ ) {
if ( isValid (i , j , ar . size () , ar . at (i) . size () , explored_ar , ar)) {
explored_ar [i][j] = 1 ;
dfs_cluster (i , j , explored_ar , ar);
num_clusters ++ ;
}
}
}
return num_clusters;
}
int main ()
{
vector < vector <char>> grid = {
{} ,
};
cout << numIslands (grid) << endl;
grid = {
{ '1' , '0' , '1' , '1' , '0' , '1' , '1' } ,
};
cout << numIslands (grid) << endl;
grid = {
{ '1' , '1' , '0' , '0' , '0' } ,
{ '1' , '1' , '0' , '0' , '0' } ,
{ '0' , '0' , '1' , '0' , '0' } ,
{ '0' , '0' , '0' , '1' , '1' } ,
};
cout << numIslands (grid) << endl;
}