The Wayback Machine - https://web.archive.org/web/20240930215848/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.



Previous Article
Next Article

Similar Reads

Minimum number of Water to Land conversion to make two islands connected in a Grid
Given a 2D grid arr[][] of ‘W’ and ‘L’ where 'W' denotes water and ‘L’ denotes land, the task is to find the minimum number of water components ‘W’ that must be changed to land component ‘L’ so that two islands becomes connected. An island is the set of connected ‘L’s. Note: There can be only two disjoint islands. Examples: Input: arr[][] = {{'W',
10 min read
Minimum number of Water to Land conversion to make two islands connected in a Grid | Set 2
Given a 2D grid arr[][] of ‘W’ and ‘L’ where ‘W’ denotes water and ‘L’ denotes land, the task is to find the minimum number of water components ‘W’ that must be changed to land component ‘L’ so that two islands becomes connected. An island is the set of connected 'L's Note: There can be only two disjoint islands. Examples: Input: arr[][] = {{‘W’, ‘
13 min read
Number of Islands after changing given cell for K queries
Given two integers N and M which denote the size of a matrix where initially all the cells are 0s. There are also K queries each of type {x, y} that denotes a cell of the matrix whose value needs to be flipped from 0 to 1. The task is to find the number of islands of 1s after each query. Note: An island means a group of 1s such that they share a co
10 min read
Number of Islands in a Circular Matrix
Given a 2D Matrix world map[][] of size N * M, such that all the places covered via land are represented by ‘L’ and the rest by ‘W’. Since the world is spherical rows and columns are cyclic (before row 1 row n comes and after row n row 1 same for the column). Count the number of islands. Examples: Input: N = 4, M = 4, worldMap = [ ['L', 'W', 'W', '
8 min read
Count number of islands where every island is row-wise and column-wise separated
Given a rectangular matrix which has only two possible values 'X' and 'O'. The values 'X' always appear in form of rectangular islands and these islands are always row-wise and column-wise separated by at least one line of 'O's. Note that islands can only be diagonally adjacent. Count the number of islands in the given matrix. Examples: mat[M][N] =
14 min read
Find the number of Islands using Disjoint Set
Given a boolean 2D matrix, find the number of islands.A group of connected 1s forms an island. For example, the below matrix contains 5 islands {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} A cell in the 2D matrix can be connected to 8 neighbours. This is a variation of the standard problem: “Counting the numbe
15+ min read
Distance between closest pair of islands
Given a grid[][] containing 0s and 1s, where '0' represents water and '1' represents the land. Given that an island is a group of land (1s) surrounded by water (0s) on all sides. The task is to find the distance between the two closest islands such that: Distance between two islands is the minimum number of '0' between two islands.Only 4 - directio
15+ min read
Islands in a graph using BFS
Given a binary 2D matrix, find the number of islands. A group of connected 1s forms an island. 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: 4Explanation: The image below shows all the 4 islands in the graph Input: M[][] = {{‘1’
15+ min read
Number of factors of very large number N modulo M where M is any prime number
Given a large number N, the task is to find the total number of factors of the number N modulo M where M is any prime number. Examples: Input: N = 9699690, M = 17 Output: 1 Explanation: Total Number of factors of 9699690 is 256 and (256 % 17) = 1Input: N = 193748576239475639, M = 9 Output: 8 Explanation: Total Number of factors of 9699690 is 256 an
8 min read
Permutation of a number whose sum with the original number is equal to another given number
Given two integers A and C, the task is to check if there exists a permutation of the number A such that the sum of the number A and its permutation is equal to C. Examples: Input: A = 133, C = 446Output: YesExplanation: One of the permutation of A is 313. Therefore, sum = 133 + 313 = 446, which is equal to C. Input: A = 200, C = 201Output: No Naiv
6 min read
Minimum number of moves to make M and N equal by repeatedly adding any divisor of number to itself except 1 and the number
Given two numbers N and M, the task is to find the minimum number of moves to change N to M or -1 if it's impossible. In one move, add to the current number any of its divisors not equal to 1 and the number itself. Examples: Input: N = 4, M = 24Output: 5Explanation: the number 24 can be reached starting from 4 using 5 operations: 4->6->8->
15+ min read
Number of Strobogrammatic Number in Range [l, r] (Strobogrammatic Number III)
Given two strings l and r, which represent two integers l and r where l <= r. The task is to return the number of strobogrammatic numbers in the range [l, r]. A strobogrammatic number is a number that looks the same when rotated 180 degrees (i.e., when viewed upside down). Example: Input: l = "50", r = "100"Output: 3 Input: l = "0", r = "0"Outpu
6 min read
Given a number as a string, find the number of contiguous subsequences which recursively add up to 9
Given a number as a string, write a function to find the number of substrings (or contiguous subsequences) of the given string which recursively add up to 9. Example: Digits of 729 recursively add to 9, 7 + 2 + 9 = 18 Recur for 18 1 + 8 = 9 Examples: Input: 4189 Output: 3 There are three substrings which recursively add to 9. The substrings are 18,
6 min read
Number of times the largest perfect square number can be subtracted from N
Given a number N. At every step, subtract the largest perfect square( ? N) from N. Repeat this step while N > 0. The task is to count the number of steps that can be performed. Examples: Input: N = 85 Output: 2 First step, 85 - (9 * 9) = 4 Second step 4 - (2 * 2) = 0 Input: N = 114 Output: 4 First step, 114 - (10 * 10) = 14 Second step 14 - (3 *
7 min read
Program to calculate the number of odd days in given number of years
Given an integer N, the task is to find the number of odd days in the years from 1 to N. Odd Days: Number of odd days refer to those days that are left in a certain year(s) when it's days gets converted into weeks. Say, an ordinary year has 365 days, that is 52 weeks and one odd day. This means, out of the 365 days in an ordinary year, 364 days wil
7 min read
Check if given number is Emirp Number or not
An Emirp Number (prime spelled backwards) is a prime number that results in a different prime when its decimal digits are reversed. This definition excludes the related palindromic primes. Examples : Input : n = 13Output : 13 is Emirp!Explanation :13 and 31 are both prime numbers. Thus, 13 is an Emirp number.Input : n = 27Output : 27 is not Emirp.O
10 min read
Given a number N in decimal base, find number of its digits in any base (base b)
Given A Number n in a base 10, find the number of digits in its base b representation. Constraints : [Tex]N \in \mathbb{W} [/Tex]Whole Examples : Input : Number = 48 Base = 4 Output: 3 Explanation : (48)10 = (300)4 Input : Number = 1446 Base = 7 Output: 4 Explanation : (446)10 = (4134)7 A simple approach: convert the decimal number into the given b
8 min read
Minimum number using set bits of a given number
Given an unsigned number, find the minimum number that could be formed by using the bits of the given unsigned number. Examples : Input : 6 Output : 3 Binary representation of 6 is 0000....0110. Smallest number with same number of set bits 0000....0011. Input : 11 Output : 7 Simple Approach: 1. Find binary representation of the number using simple
4 min read
Queries on sum of odd number digit sums of all the factors of a number
Given Q queries. Each query contain a positive integer n. The task is to output the sum of sum of odd number digit contained in all the divisors of n.Examples : Input : Q = 2, n1 = 10, n2 = 36 Output : 7 18 For Query1, Divisors of 10 are 1, 2, 5, 10. Sum of odd digits in 1 is 1, in 2 is 0, in 5 is 5, in 10 is 1. So, sum became 7.For Query 2, Diviso
9 min read
Number whose XOR sum with given array is a given number k
Given an array of N numbers and a number K. The task is to insert a number in the given array such that the bitwise XOR of all the elements in the new array equals the given input K. Examples: Input: a = {1, 2, 3, 4, 5}, k = 10Output: 11 Explanation: 1 ^ 2 ^ 3 ^ 4 ^ 5 ^ 11 = 10 Input: A[] = { 12, 23, 34, 56, 78 }, k = 6Output: 73 Approach: The basi
5 min read
Number which has the maximum number of distinct prime factors in the range M to N
Given two numbers M and N. The task is to print the number which has the maximum number of distinct prime factors of numbers in range M and N. If there exist multiple numbers, print the smallest one. Examples: Input: a=4, b=10 Output: 6 Number of distinct Prime Factors of 4 is 1 Number of distinct Prime Factors of 5 is 1 Number of distinct Prime Fa
10 min read
Check if a M-th fibonacci number divides N-th fibonacci number
Given two numbers M and N, the task is to check if the M-th and N-th Fibonacci numbers perfectly divide each other or not.Examples: Input: M = 3, N = 6 Output: Yes F(3) = 2, F(6) = 8 and F(6) % F(3) = 0 Input: M = 2, N = 9 Output: Yes A naive approach will be to find the N-th and M-th Fibonacci numbers and check if they are perfectly divisible or n
8 min read
Check if a number has same number of set and unset bits
Given a number N, the task is to check whether the count of the set and unset bits in the given number are same. Examples: Input: 12Output: Yes1100 is the binary representation of 12which has 2 set and 2 unset bits Input: 14Output: No Approach: Traverse in the binary representation of the given number, check if the leftmost bit is set or not using
5 min read
Count number of triplets with product equal to given number with duplicates allowed | Set-2
Given an array of positive integers(may contain duplicates) and a number ‘m’, find the number of unordered triplets ((Ai, Aj, Ak) and (Aj, Ai, Ak) and other permutations are counted as one only) with product equal to ‘m’. Examples: Input: arr[] = { 1, 4, 6, 2, 3, 8}, M = 24 Output: 3 The triplets are {1, 4, 6} {1, 3, 8} {4, 2, 3} Input: arr[] = { 0
14 min read
Number of ways to represent a number as sum of k fibonacci numbers
Given two numbers N and K. Find the number of ways to represent N as the sum of K Fibonacci numbers. Examples: Input : n = 12, k = 1 Output : 0 Input : n = 13, k = 3 Output : 2 Explanation : 2 + 3 + 8, 3 + 5 + 5. Approach: The Fibonacci series is f(0)=1, f(1)=2 and f(i)=f(i-1)+f(i-2) for i>1. Let's suppose F(x, k, n) be the number of ways to for
8 min read
Count number of triplets with product equal to given number | Set 2
Given an array of distinct integers(considering only positive numbers) and a number ‘m’, find the number of triplets with the product equal to ‘m’. Examples: Input: arr[] = { 1, 4, 6, 2, 3, 8} m = 24 Output: 3 Input: arr[] = { 0, 4, 6, 2, 3, 8} m = 18 Output: 0 An approach with O(n) extra space has already been discussed in previous post. In this p
7 min read
Count number of triplets with product equal to given number with duplicates allowed
Given an array of positive integers (may contain duplicates), the task is to find the number of triplets whose product is equal to a given number t. Examples: Input: arr = [1, 31, 3, 1, 93, 3, 31, 1, 93] t = 93 Output: 18 Input: arr = [4, 2, 4, 2, 3, 1] t = 8 Output: 4 [(4, 2, 1), (4, 2, 1), (2, 4, 1), (4, 2, 1)] Naive Approach: The easiest way to
15+ min read
Check if a number with even number of digits is palindrome or not
Given a number N containing an even number of digits. The task is to check whether that number is palindrome or not. Examples: Input: N = 123321 Output: Palindrome Input: 1234 Output: Not palindrome A Naive Approach is to traverse from the front and back of that number and stop where they do not match.An Efficient Approach is to use the below fact:
4 min read
Number of ways to divide a given number as a set of integers in decreasing order
Given two numbers [Tex]a [/Tex]and [Tex]m [/Tex]. The task is to find the number of ways in which a can be represented by a set [Tex]\{n_1, n_2, ...., n_c\} [/Tex]such that [Tex]a >= n_1 > n_2 > ... > n_m > 0 [/Tex]and the summation of these numbers is equal to a. Also [Tex]1 <= c <= m [/Tex](maximum size of the set cannot exce
8 min read
First triangular number whose number of divisors exceeds N
Given a number N, find the first triangular number whose number of divisors exceeds N. Triangular numbers are sums of natural numbers, i. e., of the form x*(x+1)/2. First few triangular numbers are 1, 3, 6, 10, 15, 21, 28, ...Examples: Input: N = 2 Output: 6 6 is the first triangular number with more than 2 factors.Input: N = 4 Output: 28 A naive s
13 min read