Count Reachable Cell Clusters in a Grid
Trees & GraphsAuto-graded · 21 test casesLast updated
Tests grid-based connected-components detection using flood-fill or DFS, covering neighbor connectivity, visited-state tracking, and iterative traversal.
Count Reachable Cell Clusters in a Grid
You are given an m × n grid of characters. Each cell contains either 'Z' (an open cell) or '#' (a wall). Two open cells belong to the same cluster when you can travel between them by moving only up, down, left, or right through open cells — diagonal moves are not allowed.
Write a function that counts how many distinct clusters exist in the grid.
Input
grid: a 2-D list of strings, where every element is either'Z'or'#'.mrows,ncolumns (m = len(grid),n = len(grid[0])).
Output
Return a single integer: the number of clusters.
Rules and edge cases
- Only 4-directional adjacency (up, down, left, right) forms a connection. Two
'Z'cells that touch only at a corner are in separate clusters. - An empty grid (
[]) or a grid whose only row is empty ([[]]) contains zero clusters. - A grid with no
'Z'cells contains zero clusters. - A single
'Z'cell with no open neighbors is a cluster of size one.
Constraints
0 ≤ m, n ≤ 1000- Every cell is exactly
'Z'or'#' - The grid may be mutated by your solution (in-place marking is acceptable)
Examples
Example 1
Input: count_zones([['Z', '#', 'Z'], ['Z', '#', '#'], ['#', 'Z', 'Z']])
Output: 3
Example 2
Input: count_zones([['Z', 'Z', '#'], ['#', 'Z', '#'], ['Z', '#', 'Z']])
Output: 3
Example 3
Input: count_zones([[]])
Output: 0
Example 4
Input: count_zones([['#', '#'], ['#', '#']])
Output: 0
Hints
Hint 1
Scan every cell. The first time you encounter a 'Z' you have found a new cluster — start a traversal from there to mark every cell that belongs to it before moving on.
Hint 2
To avoid counting the same cell twice, overwrite each 'Z' with '#' as soon as you add it to your traversal frontier. That way the outer scan skips it automatically.
Hint 3
Use an explicit stack (iterative DFS) rather than recursion. A long, winding cluster in a large grid can exceed Python's default recursion limit of ~1000 frames.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem is equivalent to counting connected components in an undirected graph: nodes are 'Z' cells, and edges connect 4-directionally adjacent 'Z' cells.
Algorithm
- Walk every cell in row-major order.
- When you land on a
'Z', you have found a cluster that has not been counted yet. Increment the counter. - Immediately overwrite that cell with
'#'and push it onto a stack. - Run an iterative DFS: pop a cell, check its four neighbors, and for each neighbor that is still
'Z', overwrite it with'#'and push it. Continue until the stack is empty — the entire cluster is now marked. - The outer loop continues and will never re-enter a cell that was part of this cluster.
Why it is correct
Every cluster is counted exactly once. The first cell of any cluster that the outer scan reaches is still 'Z' (nothing outside the cluster could have turned it to '#'), so the counter increments. The flood-fill then converts every cell in that cluster before the outer scan can see them, preventing any double-counting.
Cells are marked '#' when pushed, not when popped. This is important: if you mark on pop, multiple neighbors can push the same cell before it is ever popped, inflating the stack and the work done. Marking on push guarantees each cell is queued at most once.
Why iterative DFS over recursion
Python's default recursion limit is roughly 1 000 frames. A single serpentine cluster in a 1 000 × 1 000 grid could be 1 000 000 cells deep and would crash a recursive implementation. The explicit stack avoids this entirely.
Mutating the input
The solution overwrites 'Z' with '#' in place, eliminating the need for a separate visited matrix. This is the minimal-space choice, but it modifies the caller's grid. If the original grid must be preserved, either deep-copy it before calling (O(m·n) extra space) or do a second pass to restore marked cells after counting (O(1) extra space, O(m·n) time).
Complexity
| Time | O(m · n) — each cell is visited once by the outer loop and pushed/popped at most once by the DFS. |
| Space | O(m · n) worst case for the explicit stack (e.g., an all-'Z' grid). No additional visited structure is needed because the grid itself records state. |
Edge cases
[]or[[]]— guarded by the opening check, returns0.- All
'#'— the outer loop never triggers a flood-fill, returns0. - All
'Z'— one flood-fill covers everything, returns1. [['Z']]— single open cell, returns1.- Diagonal-only contact, e.g.
[['Z','#'],['#','Z']]— returns2because diagonals do not connect.
Reference solution
from typing import List
def count_zones(grid: List[List[str]]) -> int:
if not grid or not grid[0]:
return 0
rows, cols = len(grid), len(grid[0])
clusters = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] != 'Z':
continue
# New cluster found — flood-fill to mark all connected open cells.
clusters += 1
grid[r][c] = '#' # mark on push, not on pop
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 grid[nr][nc] == 'Z':
grid[nr][nc] = '#' # mark immediately to avoid duplicate pushes
stack.append((nr, nc))
return clusters