Tally Separate Clusters of Ones in a Binary Matrix
Trees & GraphsAuto-graded · 19 test casesLast updated
Count 4-directionally connected clusters of 1s in a binary matrix using graph traversal, with care for visited tracking, empty inputs, and deep clusters.
You are given a rectangular matrix matrix made of integers, where a cell holding 1 is "filled" and any other value is "empty". Two filled cells belong to the same cluster if you can get from one to the other by repeatedly stepping to a filled cell directly above, below, left, or right. Diagonal neighbors are not connected.
Return the total number of distinct clusters of filled cells.
Details
- Only cells equal to exactly
1count as filled; every other value is treated as empty. - If the matrix has no rows, or its rows have no columns, the answer is
0. - A matrix with no filled cells has
0clusters. - Do not assume clusters are small: a single cluster may cover the entire matrix, so a naive recursive traversal may exceed Python's recursion limit. Prefer an approach that is safe for large inputs.
Constraints
matrixhasmrows andncolumns, where0 <= m, n, and all rows have the same length.- Each cell is an integer; only the value
1marks a filled cell. - Adjacency is 4-directional only (up, down, left, right).
- The function must return an integer.
- Aim for
O(m * n)time.
Examples
Example 1
Input: count_clusters([[1, 1, 0, 0], [1, 0, 0, 1], [0, 0, 1, 1]])
Output: 2
Example 2
Input: count_clusters([[1, 1, 0], [0, 1, 0], [0, 0, 1]])
Output: 2
Example 3
Input: count_clusters([[0, 0], [0, 0]])
Output: 0
Hints
Hint 1
Think of each filled cell as a node in a graph, with edges to filled orthogonal neighbors. The answer is the number of connected components.
Hint 2
Scan the matrix cell by cell. When you meet a filled cell you have not seen yet, you have found a new cluster: increase the count and traverse everything reachable from it, marking those cells as seen.
Hint 3
Use an explicit stack instead of recursion to avoid depth limits, and mark a cell as seen when you push it (not when you pop it) so it is never added twice. Check bounds before indexing.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat the matrix as an implicit graph: every cell equal to 1 is a node, and two nodes are joined when they are orthogonal neighbors. A cluster is a connected component of this graph, so the task is to count connected components.
- Handle the degenerate case: if there are no rows or no columns, return
0. - Keep a
seentable (one byte per cell) so no cell is processed twice. This also leaves the input matrix unmodified. - Scan all cells in row-major order. When you find a filled cell that is not yet seen, you have discovered a new cluster, so increment the counter.
- From that cell, run a depth-first traversal using an explicit stack. Mark each cell as seen at the moment it is pushed, then pop cells and push their unseen, in-bounds, filled orthogonal neighbors.
Why it is correct
- Every cluster is counted at least once. The scan reaches every cell. The first cell of a cluster that the scan encounters is unseen, because only a traversal started inside that same cluster could have marked it, and none has run yet.
- Every cluster is counted at most once. The traversal from that first cell reaches all cells connected to it, and marks them all, so the scan skips them afterwards.
- Clusters do not merge. The traversal only steps onto in-bounds cells equal to
1via the four orthogonal moves, so it never crosses empty cells or touches diagonals.
Marking on push (rather than on pop) guarantees each cell enters the stack at most once, which keeps the stack bounded by the cluster size. Using an explicit stack rather than recursion avoids RecursionError on large or snake-shaped clusters. Bounds are checked before indexing because negative indices would silently wrap around in Python.
Complexity
- Time:
O(m * n). Each cell is scanned once, and each filled cell is pushed and popped at most once, checking four neighbors. - Space:
O(m * n)for the seen table plus, in the worst case, the stack.
Reference solution
from typing import List
def count_clusters(matrix: List[List[int]]) -> int:
if not matrix or not matrix[0]:
return 0
rows, cols = len(matrix), len(matrix[0])
seen = [bytearray(cols) for _ in range(rows)]
clusters = 0
for r in range(rows):
for c in range(cols):
if matrix[r][c] != 1 or seen[r][c]:
continue
clusters += 1
seen[r][c] = 1
stack = [(r, c)]
while stack:
cr, cc = stack.pop()
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = cr + dr, cc + dc
if (
0 <= nr < rows
and 0 <= nc < cols
and matrix[nr][nc] == 1
and not seen[nr][nc]
):
seen[nr][nc] = 1
stack.append((nr, nc))
return clusters