Cluster Counting on a Grid with King-Move Adjacency
Trees & GraphsAuto-graded · 26 test casesLast 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
0and1.
Constraints
0 <= rows, columns <= 1,000rows * columns <= 1,000,000- Each cell is either
0or1.
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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat every filled cell as a node in an implicit graph, with an edge between two filled cells whenever they are within one row and one column of each other. Each cell therefore has up to eight neighbors. The answer is the number of connected components of this graph.
- Return
0immediately if the grid has no rows or no columns. - Keep a
seenmatrix of the same shape as the grid. - Scan the cells in row-major order. When you hit a
1that is not yet seen, you have found a new cluster: increment the counter. - Run a breadth-first search from that cell over all eight directions, marking every filled cell reached. Mark a cell the moment it is added to the queue so that it is never queued more than once.
An explicit queue is used instead of recursion, because a single cluster can contain up to a million cells and recursion would exceed Python's stack limits.
Why it is correct
- A BFS from a start cell visits exactly the filled cells reachable from it via linked cells, which is its whole cluster, and nothing else.
- After the BFS, every cell in that cluster is marked, so the outer scan can never start a second search inside it. Each cluster therefore increments the counter at most once.
- Every filled cell is examined by the outer scan, so each cluster is discovered at least once. Hence the counter equals the number of clusters.
Complexity
Let N = rows * columns.
- Time:
O(N). Each cell is scanned once and each filled cell is queued at most once, with a constant eight neighbor checks. - Space:
O(N)for theseenmatrix and, in the worst case, the queue.
Reference solution
from typing import List
from collections import deque
def count_clusters_king(grid: List[List[int]]) -> int:
if not grid or not grid[0]:
return 0
rows, cols = len(grid), len(grid[0])
seen = [[False] * cols for _ in range(rows)]
moves = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
clusters = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] != 1 or seen[r][c]:
continue
clusters += 1
seen[r][c] = True
queue = deque([(r, c)])
while queue:
cr, cc = queue.popleft()
for dr, dc in moves:
nr, nc = cr + dr, cc + dc
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1 and not seen[nr][nc]:
seen[nr][nc] = True
queue.append((nr, nc))
return clusters