Connected Groups of 1s

Last Updated : 13 Jun, 2026

Given an n × m binary grid, count the number of connected groups formed by cells containing 1. Two cells belong to the same group if they are adjacent horizontally or vertically. Diagonal adjacency is not considered.

Examples:

Input: n = 3, m = 4, grid[][] = [[1, 0, 1, 1], [1, 0, 0, 0], [0, 0, 1, 1]]
Output: 3
Explanation: The grid with highlighted 3 groups

Input: grid = [[1, 1], [1, 1]]
Output: 1
Explanation: All 1s are connected

DFS Traversal - O(n × m) Time and O(n × m) Space

Traverse the grid and whenever a land cell (1) is found, start a DFS to visit and mark all connected land cells. Each DFS call counts as one group.

  • Initialize groups = 0
  • Scan each cell in grid
  • If cell is 1, increment groups and call DFS from that cell
  • In DFS, mark current cell as visited (set to 0)
  • Explore all 4 adjacent directions recursively visit all connected land cells
C++
#include <iostream>
#include <vector>
using namespace std;

// Visit all connected land cells
void dfs(int row, int col, vector<vector<int>> &grid)
{

    int n = grid.size();
    int m = grid[0].size();

    // Mark current cell as visited
    grid[row][col] = 0;

    int dr[] = {-1, 1, 0, 0};
    int dc[] = {0, 0, -1, 1};

    for (int k = 0; k < 4; k++)
    {

        int nr = row + dr[k];
        int nc = col + dc[k];

        // Visit all valid neighbouring land cells
        if (nr >= 0 && nr < n && nc >= 0 && nc < m && grid[nr][nc] == 1)
        {

            dfs(nr, nc, grid);
        }
    }
}

int countGroups(vector<vector<int>> &grid)
{

    int n = grid.size();
    int m = grid[0].size();

    int groups = 0;

    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {

            // New group found
            if (grid[i][j] == 1)
            {

                groups++;

                // Remove the entire connected component
                dfs(i, j, grid);
            }
        }
    }

    return groups;
}

int main()
{

    vector<vector<int>> grid = {{1, 0, 1, 0}, {1, 1, 0, 0}, {0, 0, 1, 1}, {0, 0, 0, 1}};

    cout << "Number of Groups = " << countGroups(grid);

    return 0;
}
Java
// Java program to count number of groups (connected components) in a grid using DFS
import java.util.*;

class GfG {
    
    // Visit all connected land cells
    static void dfs(int row, int col, int[][] grid) {
        int n = grid.length;
        int m = grid[0].length;
        
        // Mark current cell as visited
        grid[row][col] = 0;
        
        int[] dr = {-1, 1, 0, 0};
        int[] dc = {0, 0, -1, 1};
        
        for (int k = 0; k < 4; k++) {
            int nr = row + dr[k];
            int nc = col + dc[k];
            
            // Visit all valid neighbouring land cells
            if (nr >= 0 && nr < n && nc >= 0 && nc < m && grid[nr][nc] == 1) {
                dfs(nr, nc, grid);
            }
        }
    }
    
    static int countGroups(int[][] grid) {
        int n = grid.length;
        int m = grid[0].length;
        
        int groups = 0;
        
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                // New group found
                if (grid[i][j] == 1) {
                    groups++;
                    // Remove the entire connected component
                    dfs(i, j, grid);
                }
            }
        }
        
        return groups;
    }
    
    public static void main(String[] args) {
        int[][] grid = {
            {1, 0, 1, 0},
            {1, 1, 0, 0},
            {0, 0, 1, 1},
            {0, 0, 0, 1}
        };
        
        System.out.println("Number of Groups = " + countGroups(grid));
    }
}
Python
# Python program to count number of groups (connected components) in a grid using DFS

# Visit all connected land cells
def dfs(row, col, grid):
    n = len(grid)
    m = len(grid[0])
    
    # Mark current cell as visited
    grid[row][col] = 0
    
    dr = [-1, 1, 0, 0]
    dc = [0, 0, -1, 1]
    
    for k in range(4):
        nr = row + dr[k]
        nc = col + dc[k]
        
        # Visit all valid neighbouring land cells
        if 0 <= nr < n and 0 <= nc < m and grid[nr][nc] == 1:
            dfs(nr, nc, grid)

def countGroups(grid):
    n = len(grid)
    m = len(grid[0])
    
    groups = 0
    
    for i in range(n):
        for j in range(m):
            # New group found
            if grid[i][j] == 1:
                groups += 1
                # Remove the entire connected component
                dfs(i, j, grid)
    
    return groups

# Driver code
if __name__ == "__main__":
    grid = [
        [1, 0, 1, 0],
        [1, 1, 0, 0],
        [0, 0, 1, 1],
        [0, 0, 0, 1]
    ]
    
    print(f"Number of Groups = {countGroups(grid)}")
C#
// C# program to count number of groups (connected components) in a grid using DFS
using System;

class GfG {
    
    // Visit all connected land cells
    static void dfs(int row, int col, int[,] grid) {
        int n = grid.GetLength(0);
        int m = grid.GetLength(1);
        
        // Mark current cell as visited
        grid[row, col] = 0;
        
        int[] dr = {-1, 1, 0, 0};
        int[] dc = {0, 0, -1, 1};
        
        for (int k = 0; k < 4; k++) {
            int nr = row + dr[k];
            int nc = col + dc[k];
            
            // Visit all valid neighbouring land cells
            if (nr >= 0 && nr < n && nc >= 0 && nc < m && grid[nr, nc] == 1) {
                dfs(nr, nc, grid);
            }
        }
    }
    
    static int countGroups(int[,] grid) {
        int n = grid.GetLength(0);
        int m = grid.GetLength(1);
        
        int groups = 0;
        
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                // New group found
                if (grid[i, j] == 1) {
                    groups++;
                    // Remove the entire connected component
                    dfs(i, j, grid);
                }
            }
        }
        
        return groups;
    }
    
    static void Main(string[] args) {
        int[,] grid = {
            {1, 0, 1, 0},
            {1, 1, 0, 0},
            {0, 0, 1, 1},
            {0, 0, 0, 1}
        };
        
        Console.WriteLine("Number of Groups = " + countGroups(grid));
    }
}
JavaScript
// JavaScript program to count number of groups (connected components) in a grid using DFS

// Visit all connected land cells
function dfs(row, col, grid) {
    const n = grid.length;
    const m = grid[0].length;
    
    // Mark current cell as visited
    grid[row][col] = 0;
    
    const dr = [-1, 1, 0, 0];
    const dc = [0, 0, -1, 1];
    
    for (let k = 0; k < 4; k++) {
        const nr = row + dr[k];
        const nc = col + dc[k];
        
        // Visit all valid neighbouring land cells
        if (nr >= 0 && nr < n && nc >= 0 && nc < m && grid[nr][nc] === 1) {
            dfs(nr, nc, grid);
        }
    }
}

function countGroups(grid) {
    const n = grid.length;
    const m = grid[0].length;
    
    let groups = 0;
    
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < m; j++) {
            // New group found
            if (grid[i][j] === 1) {
                groups++;
                // Remove the entire connected component
                dfs(i, j, grid);
            }
        }
    }
    
    return groups;
}

// Driver code
const grid = [
    [1, 0, 1, 0],
    [1, 1, 0, 0],
    [0, 0, 1, 1],
    [0, 0, 0, 1]
];

console.log("Number of Groups = " + countGroups(grid));

Output
Number of Groups = 3

BFS Traversal - O(n × m) Time and O(n × m) Space

Traverse the grid. When land cell (1) is found, start BFS to visit and mark all connected land cells. Each BFS call counts as one group.

  • Initialize groups = 0
  • Scan each cell in grid
  • If cell is 1, increment groups and call BFS from that cell
  • In BFS, mark current cell as visited (set to 0)
  • Use queue to process all connected cells. Explore all 4 adjacent directions
  • Add unvisited 1 cells to queue
C++
#include <iostream>
#include <queue>
#include <vector>
using namespace std;

// Visit all connected land cells using BFS
void bfs(int row, int col, vector<vector<int>> &grid)
{

    int n = grid.size();
    int m = grid[0].size();

    queue<pair<int, int>> q;

    q.push({row, col});

    // Mark starting cell as visited
    grid[row][col] = 0;

    int dr[] = {-1, 1, 0, 0};
    int dc[] = {0, 0, -1, 1};

    while (!q.empty())
    {

        auto [r, c] = q.front();
        q.pop();

        for (int k = 0; k < 4; k++)
        {

            int nr = r + dr[k];
            int nc = c + dc[k];

            // If neighbouring land exists,
            // mark it visited and explore later
            if (nr >= 0 && nr < n && nc >= 0 && nc < m && grid[nr][nc] == 1)
            {

                grid[nr][nc] = 0;
                q.push({nr, nc});
            }
        }
    }
}

int countGroups(vector<vector<int>> &grid)
{

    int n = grid.size();
    int m = grid[0].size();

    int groups = 0;

    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {

            // Found a new connected component
            if (grid[i][j] == 1)
            {

                groups++;

                // Visit all cells in this component
                bfs(i, j, grid);
            }
        }
    }

    return groups;
}

int main()
{

    vector<vector<int>> grid = {{1, 0, 1, 0}, {1, 1, 0, 0}, {0, 0, 1, 1}, {0, 0, 0, 1}};

    cout << "Number of Groups = " << countGroups(grid);

    return 0;
}
Java
// Java program to count number of groups (connected components) in a grid using BFS
import java.util.*;

class GfG {
    
    // Visit all connected land cells using BFS
    static void bfs(int row, int col, int[][] grid) {
        int n = grid.length;
        int m = grid[0].length;
        
        Queue<int[]> q = new LinkedList<>();
        q.add(new int[]{row, col});
        
        // Mark starting cell as visited
        grid[row][col] = 0;
        
        int[] dr = {-1, 1, 0, 0};
        int[] dc = {0, 0, -1, 1};
        
        while (!q.isEmpty()) {
            int[] cell = q.poll();
            int r = cell[0];
            int c = cell[1];
            
            for (int k = 0; k < 4; k++) {
                int nr = r + dr[k];
                int nc = c + dc[k];
                
                // If neighbouring land exists, mark it visited and explore later
                if (nr >= 0 && nr < n && nc >= 0 && nc < m && grid[nr][nc] == 1) {
                    grid[nr][nc] = 0;
                    q.add(new int[]{nr, nc});
                }
            }
        }
    }
    
    static int countGroups(int[][] grid) {
        int n = grid.length;
        int m = grid[0].length;
        
        int groups = 0;
        
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                // Found a new connected component
                if (grid[i][j] == 1) {
                    groups++;
                    // Visit all cells in this component
                    bfs(i, j, grid);
                }
            }
        }
        
        return groups;
    }
    
    public static void main(String[] args) {
        int[][] grid = {
            {1, 0, 1, 0},
            {1, 1, 0, 0},
            {0, 0, 1, 1},
            {0, 0, 0, 1}
        };
        
        System.out.println("Number of Groups = " + countGroups(grid));
    }
}
Python
# Python program to count number of groups (connected components) in a grid using BFS
from collections import deque

# Visit all connected land cells using BFS
def bfs(row, col, grid):
    n = len(grid)
    m = len(grid[0])
    
    q = deque()
    q.append((row, col))
    
    # Mark starting cell as visited
    grid[row][col] = 0
    
    dr = [-1, 1, 0, 0]
    dc = [0, 0, -1, 1]
    
    while q:
        r, c = q.popleft()
        
        for k in range(4):
            nr = r + dr[k]
            nc = c + dc[k]
            
            # If neighbouring land exists, mark it visited and explore later
            if 0 <= nr < n and 0 <= nc < m and grid[nr][nc] == 1:
                grid[nr][nc] = 0
                q.append((nr, nc))

def countGroups(grid):
    n = len(grid)
    m = len(grid[0])
    
    groups = 0
    
    for i in range(n):
        for j in range(m):
            # Found a new connected component
            if grid[i][j] == 1:
                groups += 1
                # Visit all cells in this component
                bfs(i, j, grid)
    
    return groups

# Driver code
if __name__ == "__main__":
    grid = [
        [1, 0, 1, 0],
        [1, 1, 0, 0],
        [0, 0, 1, 1],
        [0, 0, 0, 1]
    ]
    
    print(f"Number of Groups = {countGroups(grid)}")
C#
// C# program to count number of groups (connected components) in a grid using BFS
using System;
using System.Collections.Generic;

class GfG {
    
    // Visit all connected land cells using BFS
    static void bfs(int row, int col, int[,] grid) {
        int n = grid.GetLength(0);
        int m = grid.GetLength(1);
        
        Queue<Tuple<int, int>> q = new Queue<Tuple<int, int>>();
        q.Enqueue(Tuple.Create(row, col));
        
        // Mark starting cell as visited
        grid[row, col] = 0;
        
        int[] dr = {-1, 1, 0, 0};
        int[] dc = {0, 0, -1, 1};
        
        while (q.Count > 0) {
            var cell = q.Dequeue();
            int r = cell.Item1;
            int c = cell.Item2;
            
            for (int k = 0; k < 4; k++) {
                int nr = r + dr[k];
                int nc = c + dc[k];
                
                // If neighbouring land exists, mark it visited and explore later
                if (nr >= 0 && nr < n && nc >= 0 && nc < m && grid[nr, nc] == 1) {
                    grid[nr, nc] = 0;
                    q.Enqueue(Tuple.Create(nr, nc));
                }
            }
        }
    }
    
    static int countGroups(int[,] grid) {
        int n = grid.GetLength(0);
        int m = grid.GetLength(1);
        
        int groups = 0;
        
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                // Found a new connected component
                if (grid[i, j] == 1) {
                    groups++;
                    // Visit all cells in this component
                    bfs(i, j, grid);
                }
            }
        }
        
        return groups;
    }
    
    static void Main(string[] args) {
        int[,] grid = {
            {1, 0, 1, 0},
            {1, 1, 0, 0},
            {0, 0, 1, 1},
            {0, 0, 0, 1}
        };
        
        Console.WriteLine("Number of Groups = " + countGroups(grid));
    }
}
JavaScript
// JavaScript program to count number of groups (connected components) in a grid using BFS

// Visit all connected land cells using BFS
function bfs(row, col, grid) {
    const n = grid.length;
    const m = grid[0].length;
    
    let queue = [];
    queue.push([row, col]);
    
    // Mark starting cell as visited
    grid[row][col] = 0;
    
    const dr = [-1, 1, 0, 0];
    const dc = [0, 0, -1, 1];
    
    while (queue.length > 0) {
        const [r, c] = queue.shift();
        
        for (let k = 0; k < 4; k++) {
            const nr = r + dr[k];
            const nc = c + dc[k];
            
            // If neighbouring land exists, mark it visited and explore later
            if (nr >= 0 && nr < n && nc >= 0 && nc < m && grid[nr][nc] === 1) {
                grid[nr][nc] = 0;
                queue.push([nr, nc]);
            }
        }
    }
}

function countGroups(grid) {
    const n = grid.length;
    const m = grid[0].length;
    
    let groups = 0;
    
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < m; j++) {
            // Found a new connected component
            if (grid[i][j] === 1) {
                groups++;
                // Visit all cells in this component
                bfs(i, j, grid);
            }
        }
    }
    
    return groups;
}

// Driver code
const grid = [
    [1, 0, 1, 0],
    [1, 1, 0, 0],
    [0, 0, 1, 1],
    [0, 0, 0, 1]
];

console.log("Number of Groups = " + countGroups(grid));

Output
Number of Groups = 3
Comment