Counting Land Clusters on a Wrap-Around Map
Trees & GraphsAuto-graded · 22 test casesLast updated
Count connected groups of land cells on a grid whose opposite edges wrap around, testing grid traversal with modular adjacency.
You are given a rectangular map stored as a list of rows. Each cell holds 1 for land or 0 for water.
The map is wrap-around: the first and last rows are neighbors, and the first and last columns are neighbors. Think of the map as drawn on the surface of a donut.
Two land cells belong to the same cluster if you can walk from one to the other by repeatedly stepping to a land cell directly above, below, left or right of the current one. Stepping off one edge brings you to the opposite edge in the same row or column. Diagonal steps are not allowed.
Return the number of distinct land clusters.
Rules and edge cases:
- Only cells whose value is exactly
1count as land. - If the grid has no rows or no columns, return
0. - A grid with no land returns
0. A grid that is entirely land returns1. - On very thin grids (one or two rows or columns), a cell's neighbors may coincide with each other or with the cell itself. This does not change the cluster count.
- Do not worry about modifying the input; you may copy it or leave it unchanged.
Constraints
0 <= m, nwheremis the number of rows andnis the number of columns.- All rows have the same length.
- The grid can be large (for example, 1000 x 1000), so avoid deep recursion.
- Each value is an integer; only
1is land.
Examples
Example 1
Input: count_wrapped_clusters([[1, 0, 0, 1], [0, 0, 0, 0], [1, 0, 0, 1]])
Output: 1
Example 2
Input: count_wrapped_clusters([[1, 1, 0], [0, 0, 0], [0, 0, 1]])
Output: 2
Example 3
Input: count_wrapped_clusters([[1, 1], [1, 1]])
Output: 1
Hints
Hint 1
Treat each land cell as a graph node. Its neighbors are the four adjacent cells, but with indices taken modulo the number of rows or columns.
Hint 2
Scan all cells. When you meet an unvisited land cell, increment the answer and flood-fill its whole cluster so it is never counted again.
Hint 3
Use an explicit stack or queue rather than recursion, and mark cells visited when you push them. Python's modulo operator already maps -1 to the last index.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Model the grid as a graph: each land cell is a node, and two land cells are joined by an edge if they are 4-directional neighbors on the wrap-around map. The answer is the number of connected components in this graph.
The only change from the standard flat-grid version is the neighbor function. For a cell (r, c) in an m x n grid, the neighbors are:
((r - 1) % m, c)and((r + 1) % m, c)(r, (c - 1) % n)and(r, (c + 1) % n)
Python's % returns a non-negative value, so -1 % m == m - 1, and no special boundary handling is needed.
Algorithm:
- Return
0if the grid is empty or has empty rows. - Keep a separate
seenmatrix so the input stays unchanged. - Scan every cell. When you find a land cell that is not yet seen, add one to the counter and flood-fill from it with an explicit stack, marking cells as seen when they are pushed.
- Return the counter.
Why it is correct
Each flood-fill visits exactly the cells reachable from its start, which is that cell's whole cluster, and marks all of them. A new fill only starts from an unseen land cell, which cannot belong to any previously explored cluster. So every cluster is counted exactly once. When dimensions are 1 or 2, neighbors may repeat or equal the cell itself, but the seen check makes these harmless.
An explicit stack avoids Python's recursion limit on large all-land grids. Marking on push means each cell enters the stack at most once.
Complexity
- Time:
O(m * n), since each cell is pushed once and inspects four neighbors. - Space:
O(m * n)for theseenmatrix and the stack.
An alternative is a disjoint-set union: union each land cell with its wrapped right and down neighbors, decrementing a counter that starts at the number of land cells whenever a union merges two different sets. This has the same asymptotic cost, up to the inverse-Ackermann factor.
Reference solution
from typing import List
def count_wrapped_clusters(grid: List[List[int]]) -> int:
if not grid or not grid[0]:
return 0
m, n = len(grid), len(grid[0])
seen = [[False] * n for _ in range(m)]
clusters = 0
for r in range(m):
for c in range(n):
if grid[r][c] != 1 or seen[r][c]:
continue
clusters += 1
seen[r][c] = True
stack = [(r, c)]
while stack:
row, col = stack.pop()
for nr, nc in (
((row - 1) % m, col),
((row + 1) % m, col),
(row, (col - 1) % n),
(row, (col + 1) % n),
):
if grid[nr][nc] == 1 and not seen[nr][nc]:
seen[nr][nc] = True
stack.append((nr, nc))
return clusters