The Wayback Machine - https://web.archive.org/web/20250110100815/https://www.geeksforgeeks.org/find-the-number-of-islands-using-dfs/
Open In App

Number of Islands

Last Updated : 17 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a binary 2D matrix, find the number of islands. A group of connected 1s forms an island. For example, the below matrix contains 4 islands.

Examples:

Input: M[][] = {{‘1’, ‘1’, ‘0’, ‘0’, ‘0’},
                         {‘0’, ‘1’, ‘0’, ‘0’, ‘1’},
                         {‘1’, ‘0’, ‘0’, ‘1’, ‘1’},
                        {‘0’, ‘0’, ‘0’, ‘0’, ‘0’},
                       {‘1’, ‘0’, ‘1’, ‘1’, ‘0’}}
Output: 4
Explanation: The image below shows all the 4 islands in the graph

island

Four islands in the matrix

Input: M[][] = {{‘1’, ‘1’},
                         {‘1’, ‘1’}}
Output: 1
All elements are 1, hence there is only one island

Input: M[][] = {{‘0’, ‘0’},
                         {‘0’, ‘0’}}
Output: 0
All elements are 0, hence no islands.

Background

This is a variation of the standard problem: “Counting the number of connected components in an undirected graph”.  Let us understand what is a connected component. A connected component of an undirected graph is a subgraph in which every two vertices are connected to each other by a path(s), and which is connected to no other vertices outside the subgraph.  For example, the graph shown below has three connected components. 

connected-components-in-an-undirected-graph

Connected components in an undirected graph

Using DFS and Additional Matrix

The idea is to keep an additional matrix to keep track of the visited nodes in the given matrix, and perform DFS to find the total number of islands

Follow the steps below to solve the problem:

  • Initialize count = 0 and boolean matrix, visited[][] to false.
  • For each cell of the input matrix check if the value of the current cell is 1 and is not visited , call for the DFS for all its 8 neighboring cells.
    • If the neighbor is safe to visit and is not visited already Call DFS recursively and Increment count by 1
  • Return count as the final answer.

Below is the code implementation of the above approach:

C++
// C++ Program to find the number of islands
// using DFS with additional matrix

#include <bits/stdc++.h>
using namespace std;

// A function to check if a given
// cell (r, c) can be included in DFS
bool isSafe(vector<vector<char>>& M, int r, int c, 
                vector<vector<bool>>& visited) {
    int ROW = M.size();
    int COL = M[0].size();
  
    // r is in range, c is in range, value is 1 and not 
    // yet visited
    return (r >= 0) && (r < ROW) && (c >= 0) && (c < COL) && 
                          (M[r][c] == '1' && !visited[r][c]);
}

// A utility function to do DFS for a
// 2D boolean matrix. It only considers
// the 8 neighbours as adjacent vertices
void DFS(vector<vector<char>>& M, int r, int c,
           vector<vector<bool>>& visited) {
  
    // These arrays are used to get
    // r and c numbers of 8
    // neighbours of a given cell
    vector<int> rNbr = { -1, -1, -1, 0, 0, 1, 1, 1 };
    vector<int> cNbr = { -1, 0, 1, -1, 1, -1, 0, 1 };

    // Mark this cell as visited
    visited[r][c] = true;

    // Recur for all connected neighbours
    for (int k = 0; k < 8; ++k) {
        int newR = r + rNbr[k];
        int newC = c + cNbr[k];
        if (isSafe(M, newR, newC, visited)) {
            DFS(M, newR, newC, visited);
        }
    }
}

// The main function that returns
// count of islands in a given boolean
// 2D matrix
int countIslands(vector<vector<char>>& M) {
    int ROW = M.size();
    int COL = M[0].size();
  
    // Make a bool array to mark visited cells.
    // Initially all cells are unvisited
    vector<vector<bool>> visited(ROW, vector<bool>(COL, false));

    // Initialize count as 0 and traverse through
    // all cells of the given matrix
    int count = 0;
    for (int r = 0; r < ROW; ++r) {
        for (int c = 0; c < COL; ++c) {
          
            // If a cell with value 1 is not visited yet,
            // then a new island is found
            if (M[r][c] == '1' && !visited[r][c]) {
               
                // Visit all cells in this island.
                DFS(M, r, c, visited);
                
                // increment the island count
                ++count;
            }
        }
    }
    return count;
}

int main() {
    vector<vector<char>> M = { { '1', '1', '0', '0', '0' },
                              { '0', '1', '0', '0', '1' },
                              { '1', '0', '0', '1', '1' },
                              { '0', '0', '0', '0', '0' },
                              { '1', '0', '1', '1', '0' } };

    cout << countIslands(M) << endl;

    return 0;
}
C
// C Program to find the number of islands
// using DFS with additional matrix

#include <stdbool.h>
#include <stdio.h>
#include <string.h>

#define ROW 5
#define COL 5

// A function to check if a given cell (row, col) can be
// included in DFS
int isSafe(char M[][COL], int row, int col, bool visited[][COL]) {

    // row number is in range, column number is in range and
    // value is 1 and not yet visited
    return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) &&
           (M[row][col] == '1' && !visited[row][col]);
}

// A utility function to do DFS for a 2D boolean matrix. It
// only considers the 8 neighbours as adjacent vertices
void DFS(char M[][COL], int row, int col, bool visited[][COL]) {
  
    // These arrays are used to get row and column numbers
    // of 8 neighbours of a given cell
    static int rowNbr[] = {-1, -1, -1, 0, 0, 1, 1, 1};
    static int colNbr[] = {-1, 0, 1, -1, 1, -1, 0, 1};

    // Mark this cell as visited
    visited[row][col] = true;

    // Recur for all connected neighbours
    for (int k = 0; k < 8; ++k)
        if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited))
            DFS(M, row + rowNbr[k], col + colNbr[k], visited);
}

// The main function that returns count of islands in a
// given boolean 2D matrix
int countIslands(char M[][COL]) {
  
    // Make a bool array to mark visited cells.
    // Initially all cells are unvisited
    bool visited[ROW][COL];
    memset(visited, 0, sizeof(visited));

    // Initialize count as 0 and traverse through the all
    // cells of given matrix
    int count = 0;
    for (int i = 0; i < ROW; ++i) {
        for (int j = 0; j < COL; ++j) {

            // If a cell with value 1 is not visited yet,
            // then a new island is found
            if (M[i][j] == '1' && !visited[i][j]) {
              
                  // Visit all cells in this island
                DFS(M, i, j, visited);
              
                  // increment the island count
                ++count;
            }
        }
    }
    return count;
}

int main() {
    char 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', '1', '0'}};

    printf("%d\n", countIslands(M));

    return 0;
}
Java
// Java Program to find the number of islands
// using DFS with additional matrix

import java.util.*;

public class GfG {
  
    // A function to check if a given cell (r, c) 
    // can be included in DFS
    static boolean isSafe(char[][] M, int r, int c, 
                                      boolean[][] visited) {
        int ROW = M.length;
        int COL = M[0].length;

        // r is in range, c is in range, value is '1' and not 
        // yet visited
        return r >= 0 && r < ROW && c >= 0 && c < COL 
                          && M[r][c] == '1' && !visited[r][c];
    }

    // A utility function to do DFS for a 2D matrix.
    // It only considers the 8 neighbours as adjacent vertices
    static void DFS(char[][] M, int r, int c,
                                        boolean[][] visited) {
        // These arrays are used to get r and c numbers of 8
        // neighbours of a given cell
        int[] rNbr = { -1, -1, -1, 0, 0, 1, 1, 1 };
        int[] cNbr = { -1, 0, 1, -1, 1, -1, 0, 1 };

        // Mark this cell as visited
        visited[r][c] = true;

        // Recur for all connected neighbours
        for (int k = 0; k < 8; ++k) {
            int newR = r + rNbr[k];
            int newC = c + cNbr[k];
            if (isSafe(M, newR, newC, visited)) {
                DFS(M, newR, newC, visited);
            }
        }
    }

    // function that returns count of islands in a given matrix
    static int countIslands(char[][] M) {
        int ROW = M.length;
        int COL = M[0].length;

        // Make a boolean array to mark visited cells.
        // Initially all cells are unvisited
        boolean[][] visited = new boolean[ROW][COL];

        // Initialize count as 0 and traverse through all 
          // cells of the given matrix
        int count = 0;
        for (int r = 0; r < ROW; ++r) {
            for (int c = 0; c < COL; ++c) {
              
                // If a cell with value '1' is not visited yet, 
                  // then a new island is found
                if (M[r][c] == '1' && !visited[r][c]) {
                    
                      // Visit all cells in this island.
                    DFS(M, r, c, visited);
                    
                      // increment the island count
                    ++count;
                }
            }
        }
        return count;
    }

    // Driver code
    public static void main(String[] args) {
        char[][] M = {
            { '1', '1', '0', '0', '0' },
            { '0', '1', '0', '0', '1' },
            { '1', '0', '0', '1', '1' },
            { '0', '0', '0', '0', '0' },
            { '1', '0', '1', '1', '0' }
        };

        System.out.println(countIslands(M));
    }
}
Python
# Python Program to find the number of islands
# using DFS with additional matrix

# A function to check if a given cell (r, c) 
# can be included in DFS
def is_safe(M, r, c, visited):
    ROW = len(M)
    COL = len(M[0])
  
    # r is in range, c is in range, value is 1 and not 
    # yet visited
    return (r >= 0) and (r < ROW) and (c >= 0) and (c < COL) and \
           (M[r][c] == '1' and not visited[r][c])

def DFS(M, r, c, visited):
    
    # These lists are used to get r and c numbers of 8
    # neighbours of a given cell
    rNbr = [-1, -1, -1, 0, 0, 1, 1, 1]
    cNbr = [-1, 0, 1, -1, 1, -1, 0, 1]

    # Mark this cell as visited
    visited[r][c] = True

    # Recur for all connected neighbours
    for k in range(8):
        newR = r + rNbr[k]
        newC = c + cNbr[k]
        if is_safe(M, newR, newC, visited):
            DFS(M, newR, newC, visited)

def count_islands(M):
    ROW = len(M)
    COL = len(M[0])
  
    # Make a bool array to mark visited cells.
    # Initially all cells are unvisited
    visited = [[False for _ in range(COL)] for _ in range(ROW)]

    # Initialize count as 0 and traverse through
    # all cells of the given matrix
    count = 0
    for r in range(ROW):
        for c in range(COL):
          
            # If a cell with value 1 is not visited yet,
            # then a new island is found
            if M[r][c] == '1' and not visited[r][c]:
               
                # Visit all cells in this island.
                DFS(M, r, c, visited)
                
                # increment the island count
                count += 1
    return count

if __name__ == "__main__":
    M = [ ['1', '1', '0', '0', '0'],
          ['0', '1', '0', '0', '1'],
          ['1', '0', '0', '1', '1'],
          ['0', '0', '0', '0', '0'],
          ['1', '0', '1', '1', '0'] ]

    print(count_islands(M))
C#
// C# Program to find the number of islands
// using DFS with additional matrix

using System;
using System.Collections.Generic;

class GfG {
  
    // A function to check if a given
    // cell (r, c) can be included in DFS
    static bool IsSafe(char[,] M, int r, int c, bool[,] visited) {
        int ROW = M.GetLength(0);
        int COL = M.GetLength(1);

        // r is in range, c is in range, value is 1 and not 
        // yet visited
        return (r >= 0) && (r < ROW) && (c >= 0) && (c < COL) &&
               (M[r, c] == '1' && !visited[r, c]);
    }

    // A utility function to do DFS for a
    // 2D boolean matrix. It only considers
    // the 8 neighbours as adjacent vertices
    static void DFS(char[,] M, int r, int c, bool[,] visited) {
      
        // These arrays are used to get
        // r and c numbers of 8
        // neighbours of a given cell
        int[] rNbr = { -1, -1, -1, 0, 0, 1, 1, 1 };
        int[] cNbr = { -1, 0, 1, -1, 1, -1, 0, 1 };

        // Mark this cell as visited
        visited[r, c] = true;

        // Recur for all connected neighbours
        for (int k = 0; k < 8; ++k) {
            int newR = r + rNbr[k];
            int newC = c + cNbr[k];
            if (IsSafe(M, newR, newC, visited)) {
                DFS(M, newR, newC, visited);
            }
        }
    }

    // The main function that returns
    // count of islands in a given boolean
    // 2D matrix
    static int CountIslands(char[,] M) {
        int ROW = M.GetLength(0);
        int COL = M.GetLength(1);

        // Make a bool array to mark visited cells.
        // Initially all cells are unvisited
        bool[,] visited = new bool[ROW, COL];

        // Initialize count as 0 and traverse through
        // all cells of the given matrix
        int count = 0;
        for (int r = 0; r < ROW; ++r) {
            for (int c = 0; c < COL; ++c) {
              
                // If a cell with value 1 is not visited yet,
                // then a new island is found
                if (M[r, c] == '1' && !visited[r, c]) {
                    // Visit all cells in this island
                    DFS(M, r, c, visited);

                    // increment the island count
                    ++count;
                }
            }
        }
        return count;
    }

    static void Main() {
        char[,] M = { { '1', '1', '0', '0', '0' },
                      { '0', '1', '0', '0', '1' },
                      { '1', '0', '0', '1', '1' },
                      { '0', '0', '0', '0', '0' },
                      { '1', '0', '1', '1', '0' } };

        Console.WriteLine(CountIslands(M));
    }
}
JavaScript
// JavaScript Program to find the number of islands
// using DFS with additional matrix

// A function to check if a given
// cell (r, c) can be included in DFS
function isSafe(M, r, c, visited) {
    const ROW = M.length;
    const COL = M[0].length;

    // r is in range, c is in range, value is 1 and not
    // yet visited
    return (r >= 0) && (r < ROW) && (c >= 0) && (c < COL) &&
           (M[r][c] === '1' && !visited[r][c]);
}

// A utility function to do DFS for a
// 2D boolean matrix. It only considers
// the 8 neighbours as adjacent vertices
function DFS(M, r, c, visited) {

    // These arrays are used to get
    // r and c numbers of 8
    // neighbours of a given cell
    const rNbr = [-1, -1, -1, 0, 0, 1, 1, 1];
    const cNbr = [-1, 0, 1, -1, 1, -1, 0, 1];

    // Mark this cell as visited
    visited[r][c] = true;

    // Recur for all connected neighbours
    for (let k = 0; k < 8; ++k) {
        const newR = r + rNbr[k];
        const newC = c + cNbr[k];
        if (isSafe(M, newR, newC, visited)) {
            DFS(M, newR, newC, visited);
        }
    }
}

// The main function that returns
// count of islands in a given boolean
// 2D matrix
function countIslands(M) {
    const ROW = M.length;
    const COL = M[0].length;

    // Make a bool array to mark visited cells.
    // Initially all cells are unvisited
    const visited = Array.from(Array(ROW), () => Array(COL).fill(false));

    // Initialize count as 0 and traverse through
    // all cells of the given matrix
    let count = 0;
    for (let r = 0; r < ROW; ++r) {
        for (let c = 0; c < COL; ++c) {

            // If a cell with value 1 is not visited yet,
            // then a new island is found
            if (M[r][c] === '1' && !visited[r][c]) {

                // Visit all cells in this island.
                DFS(M, r, c, visited);

                // Increment the island count
                ++count;
            }
        }
    }
    return count;
}

const M = [
    ['1', '1', '0', '0', '0'],
    ['0', '1', '0', '0', '1'],
    ['1', '0', '0', '1', '1'],
    ['0', '0', '0', '0', '0'],
    ['1', '0', '1', '1', '0']
];

console.log(countIslands(M));

Output
4

Time complexity: O(ROW x COL), where ROW is the number of rows and COL is the number of columns in the given matrix.
Auxiliary Space: O(ROW x COL), for creating an additional visited matrix.

Space Optimized DFS

If we are allowed to modify the original matrix, we can avoid an additional visited matrix. Whenever we visit a cell in matrix, we change its value to 0 so that it is not visited again

Below is the code implementation of the above approach:

C++
// C++ Program to find the number of islands
// using Space Optimized DFS  

#include <bits/stdc++.h>
using namespace std;

// A utility function to perform DFS for a 2D
// boolean matrix. It only considers the 8 neighbors
// as adjacent vertices
void DFS(vector<vector<char>>& M, int r, int c) {
    int ROW = M.size();
    int COL = M[0].size();

    // Base condition
    // if r or c is out of bounds or M[r][c] is not 1
    if (r < 0 || c < 0 || r >= ROW || c >= COL || M[r][c] != '1') {
        return;
    }

    // Mark the cell as visited by setting it to 0
    M[r][c] = '0';

    // Traverse all 8 possible directions
    vector<int> rNbr = {1, -1, 0, 0, 1, -1, 1, -1};
    vector<int> cNbr = {0, 0, 1, -1, 1, -1, -1, 1};

    for (int i = 0; i < 8; ++i) {
        int newR = r + rNbr[i];
        int newC = c + cNbr[i];
        DFS(M, newR, newC);
    }
}

// function to count the number of islands
int countIslands(vector<vector<char>>& M) {
    int ROW = M.size();
    int COL = M[0].size();
    int count = 0;

    // Traverse the entire matrix
    for (int r = 0; r < ROW; r++) {
        for (int c = 0; c < COL; c++) {
          
            // If a cell with value 1 is found
            if (M[r][c] == '1') {
                  
                  // Increment the island count
                count++;
              
                // Start DFS from the current cell
                DFS(M, r, c);
            }
        }
    }
    return count;
}

int main() {
    vector<vector<char>> M = { { '1', '1', '0', '0', '0' },
                              { '0', '1', '0', '0', '1' },
                              { '1', '0', '0', '1', '1' },
                              { '0', '0', '0', '0', '0' },
                              { '1', '0', '1', '1', '0' } };

    cout << countIslands(M) << endl;
    return 0;
}
C
// C Program to find the number of islands
// using Space Optimized DFS  

#include <stdio.h>
#include <stdlib.h>

#define ROW 5
#define COL 5

// A utility function to perform DFS for a 2D
// boolean matrix. It only considers the 8 neighbors
// as adjacent vertices
void DFS(char M[ROW][COL], int r, int c) {
    
      // Base condition
    // if r or c is out of bounds or M[r][c] is not '1'
    if (r < 0 || c < 0 || r >= ROW || c >= COL || M[r][c] != '1') {
        return;
    }

    // Mark the cell as visited by setting it to '0'
    M[r][c] = '0';

    // Traverse all 8 possible directions
    int rNbr[] = {1, -1, 0, 0, 1, -1, 1, -1};
    int cNbr[] = {0, 0, 1, -1, 1, -1, -1, 1};

    for (int i = 0; i < 8; ++i) {
        int newR = r + rNbr[i];
        int newC = c + cNbr[i];
        DFS(M, newR, newC);
    }
}

int countIslands(char M[ROW][COL]) {
    int count = 0;

    // Traverse the entire matrix
    for (int r = 0; r < ROW; r++) {
        for (int c = 0; c < COL; c++) {

            // If a cell with value '1' is found
            if (M[r][c] == '1') {

                  // Increment the island count
                count++;

                // Start DFS from the current cell
                DFS(M, r, c);
            }
        }
    }
    return count;
}

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

    printf("%d\n", countIslands(M));
    return 0;
}
Java
// Java Program to find the number of islands
// using Space Optimized DFS

import java.util.Arrays;

public class GfG {

    // A utility function to perform DFS for a 2D
    // matrix. It only considers the 8 neighbors
    // as adjacent vertices
    static void DFS(char[][] M, int r, int c) {
        int ROW = M.length;
        int COL = M[0].length;

        // Base condition
        // if r or c is out of bounds or M[r][c] is not '1'
        if (r < 0 || c < 0 || r >= ROW || c >= COL || M[r][c] != '1') {
            return;
        }

        // Mark the cell as visited by setting it to '0'
        M[r][c] = '0';

        // Traverse all 8 possible directions
        int[] rNbr = {1, -1, 0, 0, 1, -1, 1, -1};
        int[] cNbr = {0, 0, 1, -1, 1, -1, -1, 1};

        for (int i = 0; i < 8; ++i) {
            int newR = r + rNbr[i];
            int newC = c + cNbr[i];
            DFS(M, newR, newC);
        }
    }

      // function to count the number of islands
    static int countIslands(char[][] M) {
        int ROW = M.length;
        int COL = M[0].length;
        int count = 0;

        // Traverse the entire matrix
        for (int r = 0; r < ROW; r++) {
            for (int c = 0; c < COL; c++) {

                // If a cell with value '1' is found
                if (M[r][c] == '1') {

                    // Increment the island count
                    count++;

                    // Start DFS from the current cell
                    DFS(M, r, c);
                }
            }
        }
        return count;
    }

    public static void main(String[] args) {
        char[][] M = {
            { '1', '1', '0', '0', '0' },
            { '0', '1', '0', '0', '1' },
            { '1', '0', '0', '1', '1' },
            { '0', '0', '0', '0', '0' },
            { '1', '0', '1', '1', '0' }
        };

        System.out.println(countIslands(M));
    }
}
Python
# Python Program to find the number of islands
# using Space Optimized DFS

# A utility function to perform DFS for a 2D
# matrix. It only considers the 8 neighbors
# as adjacent vertices
def DFS(M, r, c):
    ROW = len(M)
    COL = len(M[0])

    # Base condition
    # if r or c is out of bounds or M[r][c] is not '1'
    if r < 0 or c < 0 or r >= ROW or c >= COL or M[r][c] != '1':
        return

    # Mark the cell as visited by setting it to '0'
    M[r][c] = '0'

    # Traverse all 8 possible directions
    rNbr = [1, -1, 0, 0, 1, -1, 1, -1]
    cNbr = [0, 0, 1, -1, 1, -1, -1, 1]

    for i in range(8):
        newR = r + rNbr[i]
        newC = c + cNbr[i]
        DFS(M, newR, newC)

# function to count the number of islands
def countIslands(M):
    ROW = len(M)
    COL = len(M[0])
    count = 0

    # Traverse the entire matrix
    for r in range(ROW):
        for c in range(COL):

            # If a cell with value '1' is found
            if M[r][c] == '1':
                # Increment the island count
                count += 1

                # Start DFS from the current cell
                DFS(M, r, c)
                
    return count

if __name__ == "__main__":
    M = [ ['1', '1', '0', '0', '0'],
          ['0', '1', '0', '0', '1'],
          ['1', '0', '0', '1', '1'],
          ['0', '0', '0', '0', '0'],
          ['1', '0', '1', '1', '0'] ]

    print(countIslands(M))
C#
// C# Program to find the number of islands
// using Space Optimized DFS

using System;
using System.Collections.Generic;

class GfG {
  
    // A utility function to perform DFS for a 2D
    // boolean matrix. It only considers the 8 neighbors
    // as adjacent vertices
    static void DFS(char[,] M, int r, int c) {
        int ROW = M.GetLength(0);
        int COL = M.GetLength(1);

        // Base condition
        // if r or c is out of bounds or M[r, c] is not '1'
        if (r < 0 || c < 0 || r >= ROW || 
                            c >= COL || M[r, c] != '1') {
            return;
        }

        // Mark the cell as visited by setting it to '0'
        M[r, c] = '0';

        // Traverse all 8 possible directions
        int[] rNbr = { 1, -1, 0, 0, 1, -1, 1, -1 };
        int[] cNbr = { 0, 0, 1, -1, 1, -1, -1, 1 };

        for (int i = 0; i < 8; i++) {
            int newR = r + rNbr[i];
            int newC = c + cNbr[i];
            DFS(M, newR, newC);
        }
    }

    // Function to count the number of islands
    static int CountIslands(char[,] M) {
        int ROW = M.GetLength(0);
        int COL = M.GetLength(1);
        int count = 0;

        // Traverse the entire matrix
        for (int r = 0; r < ROW; r++) {
            for (int c = 0; c < COL; c++) {
                  
                // If a cell with value '1' is found
                if (M[r, c] == '1') {
                    // Increment the island count
                    count++;

                    // Start DFS from the current cell
                    DFS(M, r, c);
                }
            }
        }
        return count;
    }

    static void Main() {
        char[,] M = {
            { '1', '1', '0', '0', '0' },
            { '0', '1', '0', '0', '1' },
            { '1', '0', '0', '1', '1' },
            { '0', '0', '0', '0', '0' },
            { '1', '0', '1', '1', '0' }
        };

        Console.WriteLine(CountIslands(M));
    }
}
JavaScript
// JavaScript Program to find the number of islands
// using Space Optimized DFS

// A utility function to perform DFS for a 2D
// boolean matrix. It only considers the 8 neighbors
// as adjacent vertices
function DFS(M, r, c) {
    const ROW = M.length;
    const COL = M[0].length;

    // Base condition
    // if r or c is out of bounds or M[r][c] is not '1'
    if (r < 0 || c < 0 || r >= ROW || c >= COL || M[r][c] !== '1') {
        return;
    }

    // Mark the cell as visited by setting it to '0'
    M[r][c] = '0';

    // Traverse all 8 possible directions
    const rNbr = [1, -1, 0, 0, 1, -1, 1, -1];
    const cNbr = [0, 0, 1, -1, 1, -1, -1, 1];

    for (let i = 0; i < 8; ++i) {
        const newR = r + rNbr[i];
        const newC = c + cNbr[i];
        DFS(M, newR, newC);
    }
}

// function to count the number of islands
function countIslands(M) {
    const ROW = M.length;
    const COL = M[0].length;
    let count = 0;

    // Traverse the entire matrix
    for (let r = 0; r < ROW; r++) {
        for (let c = 0; c < COL; c++) {
          
            // If a cell with value '1' is found
            if (M[r][c] === '1') {
                  
                  // Increment the island count
                count++;
              
                // Start DFS from the current cell
                DFS(M, r, c);
            }
        }
    }
    return count;
}

// Example usage
const M = [
    ['1', '1', '0', '0', '0'],
    ['0', '1', '0', '0', '1'],
    ['1', '0', '0', '1', '1'],
    ['0', '0', '0', '0', '0'],
    ['1', '0', '1', '1', '0']
];

console.log(countIslands(M));

Output
4

Time complexity: O(ROW x COL), where ROW is the number of rows and COL is the number of columns in the given matrix.
Auxiliary Space: O(ROW * COL), as to do DFS we need extra auxiliary stack space.

Using BFS

We can solve this problem using BFS as well. The idea is going to be same. We use a visited matrix to keep track if the visited cells and apply the standard queue based BFS algorithm to count islands. We increment the count whenever we see an unvisited vertex after the previous call. The time complexity and auxiliary space are going to be same as DFS. However this implementation would be faster as we do not have recursion overhead. Please refer Islands in a graph using BFS for details.

Using Disjoint Set

This solution is very intuitive if you have studied disjoint set data structures. We mainly create disjoint sets of all islands and the number of disjoint sets at the end is our answer. Please refer Find the number of Islands | Set 2 (Using Disjoint Set)  for details. The time complexity and auxiliary space wise this solution is as good as the BFS based solution.



Next Article

Similar Reads

three90RightbarBannerImg