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

Number of Islands

Last Updated : 12 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Given a binary 2D matrix of size n*m, 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: 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 – O(n*m) time and O(n*m) space

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>>& grid, int r, int c, 
                vector<vector<bool>>& visited) {
    int row = grid.size();
    int col = grid[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) && (grid[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>>& grid, 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(grid, newR, newC, visited)) {
            dfs(grid, newR, newC, visited);
        }
    }
}

// The main function that returns
// count of islands in a given boolean
// 2D matrix
int numIslands(vector<vector<char>>& grid) {
    int row = grid.size();
    int col = grid[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 (grid[r][c] == '1' && !visited[r][c]) {
               
                // Visit all cells in this island.
                dfs(grid, r, c, visited);
                
                // increment the island count
                ++count;
            }
        }
    }
    return count;
}

int main() {
    vector<vector<char>> grid = { { '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 << numIslands(grid) << 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.*;

class GfG {

    // A function to check if a given
    // cell (r, c) can be included in DFS
    static boolean isSafe(char[][] grid, int r, int c, boolean[][] visited) {
        int row = grid.length;
        int col = grid[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) && (grid[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[][] grid, 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(grid, newR, newC, visited)) {
                dfs(grid, newR, newC, visited);
            }
        }
    }

    // The main function that returns
    // count of islands in a given boolean
    // 2D matrix
    static int numIslands(char[][] grid) {
        int row = grid.length;
        int col = grid[0].length;

        // Make a bool 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 (grid[r][c] == '1' && !visited[r][c]) {
                    // Visit all cells in this island.
                    dfs(grid, r, c, visited);
                    
                    // increment the island count
                    ++count;
                }
            }
        }
        return count;
    }

    public static void main(String[] args) {
        char[][] grid = {
            { '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(numIslands(grid));
    }
}
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 isSafe(grid, r, c, visited):
    row = len(grid)
    col = len(grid[0])
    
    # r is in range, c is in range, value 
    # is 1 and not yet visited
    return (0 <= r < row) and (0 <= c < col) and (grid[r][c] == '1' and not visited[r][c])

# A utility function to do DFS for a
# 2D boolean matrix. It only considers
# the 8 neighbours as adjacent vertices
def dfs(grid, r, c, visited):
    
    # These arrays 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, newC = r + rNbr[k], c + cNbr[k]
        if isSafe(grid, newR, newC, visited):
            dfs(grid, newR, newC, visited)

# The main function that returns
# count of islands in a given boolean
# 2D matrix
def numIslands(grid):
    row = len(grid)
    col = len(grid[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 grid[r][c] == '1' and not visited[r][c]:
                
                # Visit all cells in this island.
                dfs(grid, r, c, visited)
                
                # increment the island count
                count += 1
    return count

if __name__ == "__main__":
    grid = [
        ['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(numIslands(grid))
C#
// C# Program to find the number of islands
// using DFS with additional matrix

using System;

class GfG {

    // A function to check if a given
    // cell (r, c) can be included in DFS
    static bool isSafe(char[,] grid, int r, int c, bool[,] visited) {
        int row = grid.GetLength(0);
        int col = grid.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 && grid[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[,] grid, int r, int c, bool[,] visited) {
        int[] rNbr = { -1, -1, -1, 0, 0, 1, 1, 1 };
        int[] cNbr = { -1, 0, 1, -1, 1, -1, 0, 1 };

        visited[r, c] = true;

        for (int k = 0; k < 8; k++) {
            int newR = r + rNbr[k];
            int newC = c + cNbr[k];
            if (isSafe(grid, newR, newC, visited)) {
                dfs(grid, newR, newC, visited);
            }
        }
    }

    static int numIslands(char[,] grid) {
        int row = grid.GetLength(0);
        int col = grid.GetLength(1);
        bool[,] visited = new bool[row, col];

        int count = 0;
        for (int r = 0; r < row; r++) {
            for (int c = 0; c < col; c++) {
                if (grid[r, c] == '1' && !visited[r, c]) {
                    dfs(grid, r, c, visited);
                    count++;
                }
            }
        }
        return count;
    }

    static void Main() {
        char[,] grid = {
            { '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(numIslands(grid));
    }
}
JavaScript
// JavaScript Program to find the number of islands
// using DFS with additional matrix

function isSafe(grid, r, c, visited) {
    const row = grid.length;
    const col = grid[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 && grid[r][c] === '1' && !visited[r][c];
}

function dfs(grid, r, c, visited) {
    const rNbr = [-1, -1, -1, 0, 0, 1, 1, 1];
    const cNbr = [-1, 0, 1, -1, 1, -1, 0, 1];

    visited[r][c] = true;

    for (let k = 0; k < 8; k++) {
        const newR = r + rNbr[k];
        const newC = c + cNbr[k];
        if (isSafe(grid, newR, newC, visited)) {
            dfs(grid, newR, newC, visited);
        }
    }
}

function numIslands(grid) {
    const row = grid.length;
    const col = grid[0].length;

    const visited = Array.from({ length: row }, () => Array(col).fill(false));

    let count = 0;
    for (let r = 0; r < row; r++) {
        for (let c = 0; c < col; c++) {
            if (grid[r][c] === '1' && !visited[r][c]) {
                dfs(grid, r, c, visited);
                count++;
            }
        }
    }
    return count;
}

const grid = [
    ['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(numIslands(grid));

Output
4

Using Space Optimized DFS – O(n*m) time and O(n*m) space

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 DFS with additional matrix

class GfG {
    
    // A function to check if a given
    // cell (r, c) can be included in DFS
    static boolean isSafe(char[][] grid, int r, int c) {
        int row = grid.length;
        int col = grid[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) && grid[r][c] == '1';
    }

    // A utility function to do DFS for a
    // 2D boolean matrix. It only considers
    // the 8 neighbours as adjacent vertices
    static void dfs(char[][] grid, int r, int c) {
        
        // 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
        grid[r][c] = '0';

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

    // The main function that returns
    // count of islands in a given boolean
    // 2D matrix
    static int numIslands(char[][] grid) {
        int row = grid.length;
        int col = grid[0].length;

        // 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 found,
                // then a new island is found
                if (grid[r][c] == '1') {

                    // Visit all cells in this island.
                    dfs(grid, r, c);

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

    public static void main(String[] args) {
        char[][] grid = { { '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(numIslands(grid));
    }
}
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 isSafe(grid, r, c):
    row = len(grid)
    col = len(grid[0])

    # r is in range, c is in range, value 
    # is 1 and not yet visited
    return (0 <= r < row) and (0 <= c < col) and grid[r][c] == '1'

# A utility function to do DFS for a
# 2D boolean matrix. It only considers
# the 8 neighbours as adjacent vertices
def dfs(grid, r, c):
    # These arrays 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
    grid[r][c] = '0'

    # Recur for all connected neighbours
    for k in range(8):
        newR = r + rNbr[k]
        newC = c + cNbr[k]
        if isSafe(grid, newR, newC):
            dfs(grid, newR, newC)

# The main function that returns
# count of islands in a given boolean
# 2D matrix
def numIslands(grid):
    row = len(grid)
    col = len(grid[0])

    # 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 found,
            # then a new island is found
            if grid[r][c] == '1':

                # Visit all cells in this island.
                dfs(grid, r, c)

                # increment the island count
                count += 1
    return count

if __name__ == "__main__":
    grid = [
        ['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(numIslands(grid))
C#
// C# Program to find the number of islands
// using DFS with additional matrix
using System;

class GfG {
  
    // A function to check if a given
    // cell (r, c) can be included in DFS
    static bool isSafe(char[,] grid, int r, int c) {
        int row = grid.GetLength(0);
        int col = grid.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) && grid[r, c] == '1';
    }

    // A utility function to do DFS for a
    // 2D boolean matrix. It only considers
    // the 8 neighbours as adjacent vertices
    static void dfs(char[,] grid, int r, int c) {
      
        // 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
        grid[r, c] = '0';

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

    // The main function that returns
    // count of islands in a given boolean
    // 2D matrix
    static int numIslands(char[,] grid) {
        int row = grid.GetLength(0);
        int col = grid.GetLength(1);

        // 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 found,
                // then a new island is found
                if (grid[r, c] == '1') {

                    // Visit all cells in this island.
                    dfs(grid, r, c);

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

    static void Main(string[] args) {
        char[,] grid = {
            { '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(numIslands(grid));
    }
}
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(grid, r, c) {
    let row = grid.length;
    let col = grid[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 && grid[r][c] === '1';
}

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

    // Mark this cell as visited
    grid[r][c] = '0';

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

// The main function that returns
// count of islands in a given boolean
// 2D matrix
function numIslands(grid) {
    let row = grid.length;
    let col = grid[0].length;

    // 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 found,
            // then a new island is found
            if (grid[r][c] === '1') {

                // Visit all cells in this island.
                dfs(grid, r, c);

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

let grid = [
    ['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(numIslands(grid));

Output
4

Time complexity: O(n*m)
Auxiliary Space: O(n*m) due to stack space.

Using Breadth First Search – O(n*m) time and O(n*m) space

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 – O(n*m) time and O(n*m) space

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.



Next Article

Similar Reads

three90RightbarBannerImg