Tally Separate Clusters of Occupied Cells in a Grid
Trees & GraphsAuto-graded · 19 test casesLast updated
Count groups of orthogonally touching '1' cells in a character grid, a connected-components task solved with an iterative flood fill or union-find.
Tally Separate Clusters of Occupied Cells in a Grid
A rectangular board is given as a list of rows. Each cell holds the character '1' (occupied) or '0' (empty).
Two occupied cells belong to the same cluster if you can walk from one to the other by repeatedly stepping to an occupied cell directly above, below, to the left, or to the right. Cells that touch only at a corner are not connected.
Return the total number of distinct clusters on the board.
Input
grid: a list ofmrows, each a list ofnsingle-character strings, each equal to'1'or'0'.
Output
- An integer: the number of clusters of
'1'cells.
Rules
- A board with no
'1'cells has 0 clusters. - A single
'1'cell with no orthogonal'1'neighbors is a cluster by itself. - The input should be treated as read-only; only the count matters.
Constraints
1 <= m, n <= 300- Every
grid[i][j]is either'0'or'1'. - All rows have the same length.
Examples
Example 1
Input: count_land_clusters([['1', '1', '0', '0', '0'], ['1', '1', '0', '0', '0'], ['0', '0', '1', '0', '0'], ['0', '0', '0', '1', '1']])
Output: 3
Hints
Hint 1
Think of each '1' cell as a node, with edges to its four orthogonal '1' neighbors. You are counting connected components of this graph.
Hint 2
Scan the board cell by cell. Whenever you meet a '1' you have not seen before, you have found a new cluster: add one to the answer and explore everything reachable from it.
Hint 3
A fully occupied 300 x 300 board can make recursive DFS go about 90,000 levels deep. Use an explicit queue or stack, and mark cells as visited when you push them, not when you pop them.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat every '1' cell as a node in an implicit graph, with edges to its four orthogonal '1' neighbors. A cluster is a connected component of this graph, so the task is to count components.
- Keep a
visitedmatrix of the same size as the board, so the input is left untouched. - Scan every cell in row-major order.
- When you find a
'1'that is not yet visited, a new cluster begins: increment the counter. - Run a breadth-first search from that cell, visiting every
'1'reachable through up/down/left/right moves. Mark each cell as visited at the moment it is added to the queue. - Continue scanning. Cells already visited are skipped, so no cluster is counted twice.
Why it is correct
- Counted at least once: every cluster has at least one
'1'cell, and the scan reaches every cell. The first cell of a cluster that the scan reaches is unvisited (nothing from that cluster has been explored yet), so the counter increases. - Counted at most once: a BFS from a cell visits exactly its whole component, so afterwards all its cells are marked and the scan skips them.
- No leaking between clusters: the search only moves in the four orthogonal directions, so diagonal contact never merges clusters.
Marking on enqueue (not on dequeue) ensures each cell enters the queue only once, avoiding duplicate work.
Why iterative instead of recursive
A fully occupied or snake-shaped 300 x 300 board can force recursion depth near 90,000, which exceeds Python's default recursion limit. An explicit queue (or stack) avoids that.
Complexity
- Time: O(m * n). Each cell is scanned once and each
'1'cell is enqueued once, checking 4 neighbors. - Space: O(m * n) for the visited matrix and, in the worst case, the queue.
Reference solution
from collections import deque
from typing import List
def count_land_clusters(grid: List[List[str]]) -> int:
if not grid or not grid[0]:
return 0
rows, cols = len(grid), len(grid[0])
visited = [[False] * cols for _ in range(rows)]
clusters = 0
steps = ((1, 0), (-1, 0), (0, 1), (0, -1))
for r in range(rows):
for c in range(cols):
if grid[r][c] != '1' or visited[r][c]:
continue
clusters += 1
visited[r][c] = True
queue = deque([(r, c)])
while queue:
cr, cc = queue.popleft()
for dr, dc in steps:
nr, nc = cr + dr, cc + dc
if (
0 <= nr < rows
and 0 <= nc < cols
and grid[nr][nc] == '1'
and not visited[nr][nc]
):
visited[nr][nc] = True
queue.append((nr, nc))
return clusters