KatInterview

Tally Separate Clusters of Ones in a Binary Matrix

Trees & GraphsAuto-graded · 19 test cases
MediumAuto-gradedTrees & Graphsdfsgridconnected-components

Last 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 1 count 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 0 clusters.
  • 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

  • matrix has m rows and n columns, where 0 <= m, n, and all rows have the same length.
  • Each cell is an integer; only the value 1 marks 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.