number of islands without space code example

Example: number of islands without space

#include  
using namespace std; 

#define ROW 5 
#define COL 5 

int isSafe(int M[][COL], int row, int col) 
{ 
    return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && (M[row][col] && M[row][col] != -1); 
} 

void DFS(int M[][COL], int row, int col ) 
{  
    static int rowNbr[] = { -1, -1, -1, 0, 0, 1, 1, 1 }; 
    static int colNbr[] = { -1, 0, 1, -1, 1, -1, 0, 1 }; 
     
    M[row][col] = -1; 
    
    for (int k = 0; k < 8; ++k) 
        if (isSafe(M, row + rowNbr[k], col + colNbr[k])) 
        {
            DFS(M, row + rowNbr[k], col + colNbr[k]);            
        }
             
} 

int countIslands(int M[][COL]) 
{
    int count = 0; 
    for (int i = 0; i < ROW; ++i) 
        for (int j = 0; j < COL; ++j) 
            if (M[i][j] && M[i][j] != -1) 
            {  
                DFS(M, i, j); 
                ++count; 
            } 

    return count; 
} 

int main() 
{ 
    int M[][COL] = { 
        { 1, 1, 0, 0, 0 }, 
        { 0, 1, 0, 0, 1 }, 
        { 1, 0, 0, 1, 1 }, 
        { 0, 0, 0, 0, 0 }, 
        { 1, 0, 1, 0, 1 }
        }; 

    cout << "Number of islands is: " << countIslands(M); 

    return 0; 
}

Tags:

Misc Example