The Wayback Machine - https://web.archive.org/web/20241227220123/https://www.geeksforgeeks.org/islands-in-a-graph-using-bfs/
Open In App

Islands in a graph using BFS

Last Updated : 28 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.

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.

[Naive Approach] Using BFS and Additional Matrix – O(rows * cols) Time and O(rows * cols) Space

We have discussed DFS solutions for islands. This problem can also solved by applying BFS on each component. A cell in 2D matrix can be connected to 8 neighbors. So, for every cell with value ‘1’, we process all 8 neighbors. We also keep track of the visited 1s so that they are not visited again. 

The following are the detailed steps:

  1. Initialize a boolean matrix of the same size as the given matrix to keep track of visited cells.
  2. Traverse the given matrix, and for each unvisited cell that is part of an island, perform BFS starting from that cell.
  3. In the BFS algorithm, enqueue the current cell and mark it as visited. Then, while the queue is not empty, dequeue a cell and enqueue its unvisited neighbors that are part of the same island. Mark each of these neighbors as visited.
  4. After BFS is complete, increment the island count by 1.
  5. Repeat steps 2-4 until all unvisited cells have been processed.
  6. Return the total island count.
C++
// C++ Program to find the number of islands using BFS

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

// A function to check if a given cell (r, c) 
// can be included in BFS
bool isSafe(vector<vector<char>>& M, int r, 
            int c, vector<vector<bool>>& vis) {
    int rows = M.size();
    int cols = M[0].size();
    return (r >= 0) && (r < rows) && (c >= 0) && 
         (c < cols) && (M[r][c] == '1' && !vis[r][c]);
}

// Breadth-First-Search to visit all cells in the 
// current island
void BFS(vector<vector<char>>& M, vector<vector<bool>>& vis,
                                         int sr, int sc) {
  
    // These arrays are used to get row and
    // column 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 };

    // Simple BFS first step, we enqueue
    // source and mark it as visited
    queue<pair<int, int>> q;
    q.push({sr, sc});
    vis[sr][sc] = true;

    // Next step of BFS. We take out
    // items one by one from queue and
    // enqueue their unvisited adjacent
    while (!q.empty()) {
        int r = q.front().first;
        int c = q.front().second;
        q.pop();

        // Go through all 8 adjacent
        for (int k = 0; k < 8; k++) {
            int newR = r + rNbr[k];
            int newC = c + cNbr[k];
            if (isSafe(M, newR, newC, vis)) {
                vis[newR][newC] = true;
                q.push({newR, newC});
            }
        }
    }
}

// This function returns the number of islands 
// (connected components) in a graph
int countIslands(vector<vector<char>>& M) {
  
    // Mark all cells as not visited
    int rows = M.size();
    int cols = M[0].size();
    vector<vector<bool>> vis(rows, vector<bool>(cols, false));

    // Call BFS for every unvisited vertex
    // Whenever we see an unvisited vertex,
    // we increment res (number of islands)
    // also.
    int res = 0;
    for (int r = 0; r < rows; r++) {
        for (int c = 0; c < cols; c++) {
            if (M[r][c] == '1' && !vis[r][c]) {
                BFS(M, vis, r, c);
                res++;
            }
        }
    }

    return res;
}

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);
    return 0;
}
C
// C Program to find the number of islands using BFS

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

#define ROW 5
#define COL 5

// A function to check if a given cell (r, c) can be included in BFS
bool isSafe(char M[ROW][COL], int r, int c, bool vis[ROW][COL]) {
    return (r >= 0) && (r < ROW) && (c >= 0) && 
          (c < COL) && (M[r][c] == '1' && !vis[r][c]);
}

// Breadth-First Search to visit all cells in the current island
void BFS(char M[ROW][COL], bool vis[ROW][COL], 
                             int sr, int sc) {
  
    // These arrays are used to get row and
    // column 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 };

    // Simple BFS first step, we enqueue
    // source and mark it as visited
    int queue[500][2];
    int front = 0, rear = 0;
    queue[rear][0] = sr;
    queue[rear][1] = sc;
    rear++;
    vis[sr][sc] = true;

    // Next step of BFS. We take out
    // items one by one from queue and
    // enqueue their unvisited adjacent
    while (front < rear) {
        int r = queue[front][0];
        int c = queue[front][1];
        front++;

        // Go through all 8 adjacent
        for (int k = 0; k < 8; k++) {
            int newR = r + rNbr[k];
            int newC = c + cNbr[k];
            if (isSafe(M, newR, newC, vis)) {
                vis[newR][newC] = true;
                queue[rear][0] = newR;
                queue[rear][1] = newC;
                rear++;
            }
        }
    }
}

// This function returns the number of 
// islands (connected components) in a graph
int countIslands(char M[ROW][COL]) {
  
    // Mark all cells as not visited
    bool vis[ROW][COL];
    memset(vis, 0, sizeof(vis));

    // Call BFS for every unvisited vertex
    // Whenever we see an unvisited vertex,
    // we increment res (number of islands)
    // also.
    int res = 0;
    for (int r = 0; r < ROW; r++) {
        for (int c = 0; c < COL; c++) {
            if (M[r][c] == '1' && !vis[r][c]) {
                BFS(M, vis, r, c);
                res++;
            }
        }
    }

    return res;
}

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 BFS

import java.util.LinkedList;
import java.util.Queue;

class GfG {

    // A function to check if a given cell (r, c) 
    // can be included in BFS
    static boolean isSafe(char[][] M, int r, int c, 
                                          boolean[][] vis) {
        int rows = M.length;
        int cols = M[0].length;
        return (r >= 0) && (r < rows) && (c >= 0) && 
               (c < cols) && (M[r][c] == '1' && !vis[r][c]);
    }

    // Breadth-First-Search to visit all cells in the 
    // current island
    static void BFS(char[][] M, boolean[][] vis, 
                                        int sr, int sc) {
        // These arrays are used to get row and
        // column 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 };

        // Simple BFS first step, we enqueue
        // source and mark it as visited
        Queue<int[]> q = new LinkedList<>();
        q.add(new int[]{sr, sc});
        vis[sr][sc] = true;

        // Next step of BFS. We take out
        // items one by one from queue and
        // enqueue their unvisited adjacent
        while (!q.isEmpty()) {
            int[] pos = q.poll();
            int r = pos[0];
            int c = pos[1];

            // Go through all 8 adjacent
            for (int k = 0; k < 8; k++) {
                int newR = r + rNbr[k];
                int newC = c + cNbr[k];
                if (isSafe(M, newR, newC, vis)) {
                    vis[newR][newC] = true;
                    q.add(new int[]{newR, newC});
                }
            }
        }
    }

    // This function returns the number of islands 
    // (connected components) in a graph
    static int countIslands(char[][] M) {
        
          // Mark all cells as not visited
        int rows = M.length;
        int cols = M[0].length;
        boolean[][] vis = new boolean[rows][cols];

        // Call BFS for every unvisited vertex
        // Whenever we see an unvisited vertex,
        // we increment res (number of islands)
        // also.
        int res = 0;
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                if (M[r][c] == '1' && !vis[r][c]) {
                    BFS(M, vis, r, c);
                    res++;
                }
            }
        }

        return res;
    }

    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 BFS

from collections import deque

# A function to check if a given cell (r, c) 
# can be included in BFS
def isSafe(M, r, c, vis):
    rows = len(M)
    cols = len(M[0])
    return (r >= 0) and (r < rows) and (c >= 0) and \
           (c < cols) and (M[r][c] == '1' and not vis[r][c])


# Breadth-First-Search to visit all cells in the 
# current island
def BFS(M, vis, sr, sc):
      
    # These arrays are used to get row and
    # column 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]

    # Simple BFS first step, we enqueue
    # source and mark it as visited
    q = deque([(sr, sc)])
    vis[sr][sc] = True

    # Next step of BFS. We take out
    # items one by one from queue and
    # enqueue their unvisited adjacent
    while q:
        r, c = q.popleft()

        # Go through all 8 adjacent
        for k in range(8):
            newR = r + rNbr[k]
            newC = c + cNbr[k]
            if isSafe(M, newR, newC, vis):
                vis[newR][newC] = True
                q.append((newR, newC))

# This function returns the number of islands 
# (connected components) in a graph
def countIslands(M):
  
    # Mark all cells as not visited
    rows = len(M)
    cols = len(M[0])
    vis = [[False] * cols for _ in range(rows)]

    # Call BFS for every unvisited vertex
    # Whenever we see an unvisited vertex,
    # we increment res (number of islands)
    # also.
    res = 0
    for r in range(rows):
        for c in range(cols):
            if M[r][c] == '1' and not vis[r][c]:
                BFS(M, vis, r, c)
                res += 1

    return res

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 BFS

using System;
using System.Collections.Generic;

class GfG {
  
    // A function to check if a given cell (r, c) 
    // can be included in BFS
    static bool IsSafe(char[][] M, int r, int c, bool[][] vis) {
        int rows = M.Length;
        int cols = M[0].Length;
        return (r >= 0) && (r < rows) && (c >= 0) && 
               (c < cols) && (M[r][c] == '1' && !vis[r][c]);
    }

    // Breadth-First-Search to visit all cells in the 
    // current island
    static void BFS(char[][] M, bool[][] vis, int sr, int sc) {
      
        // These arrays are used to get row and
        // column 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 };

        // Simple BFS first step, we enqueue
        // source and mark it as visited
        Queue<(int, int)> q = new Queue<(int, int)>();
        q.Enqueue((sr, sc));
        vis[sr][sc] = true;

        // Next step of BFS. We take out
        // items one by one from queue and
        // enqueue their unvisited adjacent
        while (q.Count > 0) {
            var (r, c) = q.Dequeue();

            // Go through all 8 adjacent
            for (int k = 0; k < 8; k++) {
                int newR = r + rNbr[k];
                int newC = c + cNbr[k];
                if (IsSafe(M, newR, newC, vis)) {
                    vis[newR][newC] = true;
                    q.Enqueue((newR, newC));
                }
            }
        }
    }

    // This function returns the number of islands 
    // (connected components) in a graph
    static int CountIslands(char[][] M) {
      
        // Mark all cells as not visited
        int rows = M.Length;
        int cols = M[0].Length;
        bool[][] vis = new bool[rows][];
        for (int i = 0; i < rows; i++) {
            vis[i] = new bool[cols];
        }

        // Call BFS for every unvisited vertex
        // Whenever we see an unvisited vertex,
        // we increment res (number of islands)
        // also.
        int res = 0;
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                if (M[r][c] == '1' && !vis[r][c]){
                    BFS(M, vis, r, c);
                    res++;
                }
            }
        }

        return res;
    }

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

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

// A function to check if a given cell (r, c) 
// can be included in BFS
function isSafe(M, r, c, vis) {
    const rows = M.length;
    const cols = M[0].length;
    return (r >= 0) && (r < rows) && (c >= 0) && 
           (c < cols) && (M[r][c] === '1' && !vis[r][c]);
}

// Breadth-First-Search to visit all cells in the 
// current island
function BFS(M, vis, sr, sc) {
    // These arrays are used to get row and
    // column 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 ];

    // Simple BFS first step, we enqueue
    // source and mark it as visited
    const queue = [];
    queue.push([sr, sc]);
    vis[sr][sc] = true;

    // Next step of BFS. We take out
    // items one by one from queue and
    // enqueue their unvisited adjacent
    while (queue.length > 0) {
        const [r, c] = queue.shift();

        // Go through all 8 adjacent
        for (let k = 0; k < 8; k++) {
            const newR = r + rNbr[k];
            const newC = c + cNbr[k];
            if (isSafe(M, newR, newC, vis)) {
                vis[newR][newC] = true;
                queue.push([newR, newC]);
            }
        }
    }
}

// This function returns the number of islands 
// (connected components) in a graph
function countIslands(M) {
    // Mark all cells as not visited
    const rows = M.length;
    const cols = M[0].length;
    const vis = Array.from({ length: rows }, () => Array(cols).fill(false));

    // Call BFS for every unvisited vertex
    // Whenever we see an unvisited vertex,
    // we increment res (number of islands)
    // also.
    let res = 0;
    for (let r = 0; r < rows; r++) {
        for (let c = 0; c < cols; c++) {
            if (M[r][c] === '1' && !vis[r][c]) {
                BFS(M, vis, r, c);
                res++;
            }
        }
    }

    return res;
}

// 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(rows * cols) where rows is the number of rows and cols is the number of columns in the matrix. 
Auxiliary Space: O(rows * cols ) because of the visited array

[Expected Approach] Using Space Optimized BFS – O(rows * cols) Time and O(rows + cols) Space

The idea is instead of using an additional matrix vis[][] to keep track of the visited nodes, we can change the original input matrix by marking the visited cells as ‘0’. So, every time we visit a cell with value ‘1’, we update its value to ‘0’ to avoid revisiting the same cell.

Below is the implementation of the above approach:

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

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

// A function to check if a given cell (r, c) 
// can be included in BFS
bool isSafe(vector<vector<char>>& M, int r, int c) {
    int rows = M.size();
    int cols = M[0].size();
    return (r >= 0) && (r < rows) && (c >= 0) && 
                     (c < cols) && (M[r][c] == '1');
}

// Breadth-First-Search to visit all cells in the 
// current island
void BFS(vector<vector<char>>& M, int sr, int sc) {
  
    // These arrays are used to get row and
    // column 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 };

    // Simple BFS first step, we enqueue
    // source and mark it as visited
    queue<pair<int, int>> q;
    q.push({sr, sc});
      M[sr][sc] = '0';

    // Next step of BFS. We take out
    // items one by one from queue and
    // enqueue their unvisited adjacent
    while (!q.empty()) {
        int r = q.front().first;
        int c = q.front().second;
        q.pop();

        // Go through all 8 adjacent
        for (int k = 0; k < 8; k++) {
            int newR = r + rNbr[k];
            int newC = c + cNbr[k];
            if (isSafe(M, newR, newC)) {
                M[newR][newC] = '0';
                q.push({newR, newC});
            }
        }
    }
}

// This function returns the number of islands 
// (connected components) in a graph
int countIslands(vector<vector<char>>& M) {
  
    // Mark all cells as not visited
    int rows = M.size();
    int cols = M[0].size();

    // Call BFS for every unvisited vertex
    // Whenever we see an unvisited vertex,
    // we increment res (number of islands) also.
    int res = 0;
    for (int r = 0; r < rows; r++) {
        for (int c = 0; c < cols; c++) {
            if (M[r][c] == '1') {
                BFS(M, r, c);
                res++;
            }
        }
    }

    return res;
}

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);
    return 0;
}
C
// C Program to find the number of islands using 
// Space Optimized BFS

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

#define ROW 5
#define COL 5

// A function to check if a given cell (r, c) can be included in BFS
bool isSafe(char M[ROW][COL], int r, int c) {
    return (r >= 0) && (r < ROW) && (c >= 0) && 
          (c < COL) && (M[r][c] == '1');
}

// Breadth-First Search to visit all cells in the current island
void BFS(char M[ROW][COL], int sr, int sc) {
  
    // These arrays are used to get row and
    // column 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 };

    // Simple BFS first step, we enqueue
    // source and mark it as visited
    int queue[500][2];
    int front = 0, rear = 0;
    queue[rear][0] = sr;
    queue[rear][1] = sc;
    rear++;
      M[sr][sc] = '0';

    // Next step of BFS. We take out
    // items one by one from queue and
    // enqueue their unvisited adjacent
    while (front < rear) {
        int r = queue[front][0];
        int c = queue[front][1];
        front++;

        // Go through all 8 adjacent
        for (int k = 0; k < 8; k++) {
            int newR = r + rNbr[k];
            int newC = c + cNbr[k];
            if (isSafe(M, newR, newC)) {
                queue[rear][0] = newR;
                queue[rear][1] = newC;
                  M[newR][newC] = '0';
                rear++;
            }
        }
    }
}

// This function returns the number of 
// islands (connected components) in a graph
int countIslands(char M[ROW][COL]) {

    // Call BFS for every unvisited vertex
    // Whenever we see an unvisited vertex,
    // we increment res (number of islands)
    // also.
    int res = 0;
    for (int r = 0; r < ROW; r++) {
        for (int c = 0; c < COL; c++) {
            if (M[r][c] == '1') {
                BFS(M, r, c);
                res++;
            }
        }
    }

    return res;
}

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 
// Space Optimized BFS

import java.util.LinkedList;
import java.util.Queue;

class GfG {
    
    // A function to check if a given cell (r, c) 
    // can be included in BFS
    static boolean isSafe(char[][] M, int r, int c) {
        int rows = M.length;
        int cols = M[0].length;
        return (r >= 0) && (r < rows) && (c >= 0) && 
               (c < cols) && (M[r][c] == '1');
    }

    // Breadth-First-Search to visit all cells in the 
    // current island
    static void BFS(char[][] M, int sr, int sc) {
        // These arrays are used to get row and
        // column 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 };

        // Simple BFS first step, we enqueue
        // source and mark it as visited
        Queue<int[]> q = new LinkedList<>();
        q.add(new int[] { sr, sc });
        M[sr][sc] = '0';

        // Next step of BFS. We take out
        // items one by one from queue and
        // enqueue their unvisited adjacent
        while (!q.isEmpty()) {
            int[] cell = q.poll();
            int r = cell[0];
            int c = cell[1];

            // Go through all 8 adjacent
            for (int k = 0; k < 8; k++) {
                int newR = r + rNbr[k];
                int newC = c + cNbr[k];
                if (isSafe(M, newR, newC)) {
                    M[newR][newC] = '0';
                    q.add(new int[] { newR, newC });
                }
            }
        }
    }

    // This function returns the number of islands 
    // (connected components) in a graph
    static int countIslands(char[][] M) {
        // Call BFS for every unvisited vertex
        // Whenever we see an unvisited vertex,
        // we increment res (number of islands) also.
        int rows = M.length;
        int cols = M[0].length;
        int res = 0;
        
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                if (M[r][c] == '1') {
                    BFS(M, r, c);
                    res++;
                }
            }
        }

        return res;
    }

    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 BFS

from collections import deque

# A function to check if a given cell (r, c) 
# can be included in BFS
def isSafe(M, r, c):
    rows = len(M)
    cols = len(M[0])
    return (r >= 0) and (r < rows) and (c >= 0) and \
           (c < cols) and (M[r][c] == '1')

# Breadth-First-Search to visit all cells in the 
# current island
def BFS(M, sr, sc):
    # These arrays are used to get row and
    # column 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]

    # Simple BFS first step, we enqueue
    # source and mark it as visited
    q = deque()
    q.append((sr, sc))
    M[sr][sc] = '0'

    # Next step of BFS. We take out
    # items one by one from queue and
    # enqueue their unvisited adjacent
    while q:
        r, c = q.popleft()

        # Go through all 8 adjacent
        for k in range(8):
            newR = r + rNbr[k]
            newC = c + cNbr[k]
            if isSafe(M, newR, newC):
                M[newR][newC] = '0'
                q.append((newR, newC))

# This function returns the number of islands 
# (connected components) in a graph
def countIslands(M):
    
    # Mark all cells as not visited
    rows = len(M)
    cols = len(M[0])

    # Call BFS for every unvisited vertex
    # Whenever we see an unvisited vertex,
    # we increment res (number of islands) also.
    res = 0
    for r in range(rows):
        for c in range(cols):
            if M[r][c] == '1':
                BFS(M, r, c)
                res += 1

    return res

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 BFS

using System;
using System.Collections.Generic;

class GfG {
  
    // A function to check if a given cell (r, c) 
    // can be included in BFS
    static bool IsSafe(char[][] M, int r, int c) {
        int rows = M.Length;
        int cols = M[0].Length;
        return (r >= 0) && (r < rows) && (c >= 0) &&
               (c < cols) && (M[r][c] == '1');
    }

    // Breadth-First-Search to visit all cells in the 
    // current island
    static void BFS(char[][] M, int sr, int sc) {
      
        // These arrays are used to get row and
        // column 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 };

        // Simple BFS first step, we enqueue
        // source and mark it as visited
        Queue<(int, int)> q = new Queue<(int, int)>();
        q.Enqueue((sr, sc));
        M[sr][sc] = '0';

        // Next step of BFS. We take out
        // items one by one from queue and
        // enqueue their unvisited adjacent
        while (q.Count > 0) {
            var (r, c) = q.Dequeue();

            // Go through all 8 adjacent
            for (int k = 0; k < 8; k++) {
                int newR = r + rNbr[k];
                int newC = c + cNbr[k];
                if (IsSafe(M, newR, newC)) {
                    M[newR][newC] = '0';
                    q.Enqueue((newR, newC));
                }
            }
        }
    }

    // This function returns the number of islands 
    // (connected components) in a graph
    static int CountIslands(char[][] M) {
      
        // Mark all cells as not visited
        int rows = M.Length;
        int cols = M[0].Length;

        // Call BFS for every unvisited vertex
        // Whenever we see an unvisited vertex,
        // we increment res (number of islands) also.
        int res = 0;
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                if (M[r][c] == '1') {
                    BFS(M, r, c);
                    res++;
                }
            }
        }

        return res;
    }

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

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

// A function to check if a given cell (r, c) 
// can be included in BFS
function isSafe(M, r, c) {
    const rows = M.length;
    const cols = M[0].length;
    return (r >= 0) && (r < rows) && (c >= 0) && 
           (c < cols) && (M[r][c] === '1');
}

// Breadth-First-Search to visit all cells in the 
// current island
function BFS(M, sr, sc) {
    // These arrays are used to get row and
    // column 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];

    // Simple BFS first step, we enqueue
    // source and mark it as visited
    let queue = [[sr, sc]];
    M[sr][sc] = '0';

    // Next step of BFS. We take out
    // items one by one from queue and
    // enqueue their unvisited adjacent
    while (queue.length > 0) {
        const [r, c] = queue.shift();

        // Go through all 8 adjacent
        for (let k = 0; k < 8; k++) {
            const newR = r + rNbr[k];
            const newC = c + cNbr[k];
            if (isSafe(M, newR, newC)) {
                M[newR][newC] = '0';
                queue.push([newR, newC]);
            }
        }
    }
}

// This function returns the number of islands 
// (connected components) in a graph
function countIslands(M) {
    
    // Mark all cells as not visited
    const rows = M.length;
    const cols = M[0].length;

    // Call BFS for every unvisited vertex
    // Whenever we see an unvisited vertex,
    // we increment res (number of islands) also.
    let res = 0;
    for (let r = 0; r < rows; r++) {
        for (let c = 0; c < cols; c++) {
            if (M[r][c] === '1') {
                BFS(M, r, c);
                res++;
            }
        }
    }

    return res;
}

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(rows * cols), where rows is the number of rows and cols is the number of columns in matrix M[][].
Auxiliary Space: O(rows + cols), in the worst case when all the cells are ‘1’, then at most (rows + cols) cells will be present inside the queue.



Next Article

Similar Reads

Article Tags :
Practice Tags :
three90RightbarBannerImg