KatInterview

Count Reachable Cell Clusters in a Grid

Trees & GraphsAuto-graded · 21 test cases
MediumAuto-gradedTrees & Graphsgraphsgriddfs

Last 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 '#'.
    • m rows, n columns (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.