KatInterview

Tally Separate Clusters of Occupied Cells in a Grid

Trees & GraphsAuto-graded · 19 test cases
MediumAuto-gradedTrees & Graphsgraphbfsgrid

Last 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 of m rows, each a list of n single-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.