Algorithm to find the total number of connected sets in a matrix
Data Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.
Introduction
Finding connected components in a binary matrix means counting the number of distinct groups of 1s that are connected horizontally, vertically, or diagonally. This is equivalent to counting connected components in a graph where each cell with value 1 is a node and adjacent cells are edges. The standard approach uses BFS or DFS, visiting each cell once for O(rows × cols) time complexity. Union-Find is an alternative that handles dynamic connectivity efficiently.
Problem Definition
Two cells are connected if they are adjacent in any of the 8 directions (up, down, left, right, and 4 diagonals).
Method 1: DFS (Depth-First Search)
Time: O(rows × cols). Space: O(rows × cols) for visited array and recursion stack.
Method 2: BFS (Breadth-First Search)
BFS avoids deep recursion, which matters for large matrices:
Method 3: Union-Find (Disjoint Set Union)
Union-Find is efficient for dynamic connectivity and parallel processing:
Time: O(rows × cols × α(n)) where α is the inverse Ackermann function (nearly constant).
4-Connected vs 8-Connected
The problem can define adjacency as 4-directional (no diagonals) or 8-directional (with diagonals):
In-Place Modification (No Extra Space)
If you can modify the input matrix, mark visited cells by setting them to 0:
C++ Implementation
Common Pitfalls
- Stack overflow with DFS on large matrices: Recursive DFS on a 1000×1000 matrix of all 1s creates up to 1,000,000 recursive calls, exceeding the default stack size. Use BFS (iterative) or increase the stack limit for large inputs.
- Forgetting diagonal neighbors: If the problem requires 8-connectivity (including diagonals), checking only 4 directions undercounts components. Always clarify whether diagonal adjacency counts.
- Marking visited after enqueuing in BFS: Mark cells as visited when you add them to the queue, not when you process them. Otherwise, the same cell gets added multiple times, wasting time and potentially causing duplicates.
- Modifying the matrix when it should be preserved: The in-place approach destroys the input. If you need the original matrix later, use a separate
visitedarray or make a copy first. - Off-by-one in boundary checks: Ensure
nr >= 0 && nr < rows && nc >= 0 && nc < colschecks are correct. Using<=instead of<for the upper bound accesses out-of-bounds memory (C/C++) or throws IndexError (Python).
Summary
- Use BFS or DFS to count connected components: visit each 1-cell, flood-fill its component, increment count
- Time complexity: O(rows × cols) — each cell visited at most once
- DFS is simpler to code; BFS avoids stack overflow on large matrices
- Union-Find is useful for dynamic connectivity or parallel processing
- Choose 4-connected or 8-connected based on the problem definition (diagonal adjacency)
- This is equivalent to "Number of Islands" (LeetCode 200) with 4-connectivity
Related reading
- Algorithm to find top 10 search terms
- Algorithm to find two points furthest away from each other
- Algorithm to find two repeated numbers in an array, without sorting
- Algorithm to find which number in a list sum up to a certain number
- Algorithm to generate spanning set
- Algorithm to group items in groups of 3
- Algorithm to generate a crossword
- Algorithm to generate all combinations of a string

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.