KatInterview

Cluster Counting on a Grid with King-Move Adjacency

Trees & GraphsAuto-graded · 26 test cases
MediumAuto-gradedTrees & Graphsgridbfsconnected-components

Last updated

Count groups of touching 1-cells in a binary grid where all eight surrounding cells count as neighbors, testing grid traversal and connected-component counting.

Cluster Counting on a Grid with King-Move Adjacency

You are given a rectangular grid made up of 0 and 1 values. A 1 is a filled cell and a 0 is an empty cell.

Two filled cells are linked if one can be reached from the other by a single chess-king move. In other words, the difference between their row indices is at most 1 and the difference between their column indices is at most 1 (and they are not the same cell). Horizontal, vertical, and diagonal neighbors are all linked.

A cluster is a maximal set of filled cells in which any two cells are joined by a chain of linked filled cells.

Write a function that returns how many clusters the grid contains.

Details

  • The grid may have zero rows, or rows with zero columns. In those cases, and whenever the grid has no filled cells, the answer is 0.
  • Only the number of clusters is returned; the order of clusters does not matter.
  • The input grid is rectangular (every row has the same length) and holds only 0 and 1.

Constraints

  • 0 <= rows, columns <= 1,000
  • rows * columns <= 1,000,000
  • Each cell is either 0 or 1.

Examples

Example 1

Input: count_clusters_king([[1, 0], [0, 1]])

Output: 1

Example 2

Input: count_clusters_king([[1, 0, 0], [0, 0, 1], [1, 0, 0]])

Output: 3

Hints

Hint 1

Model each filled cell as a node in an implicit graph; each node can have up to eight neighbors, not four.

Hint 2

Scan the grid; whenever you meet a filled cell you have not seen before, you have found a new cluster, so count it and flood through everything connected to it.

Hint 3

Use an explicit queue or stack instead of recursion because one cluster can span a million cells, and mark cells as seen when you add them to the queue so they are never queued twice.