Grid Land Regions: Total Count and Unique Footprints
Trees & GraphsAuto-graded · 28 test casesLast updated
Tests grid flood-fill for connected-component counting and translation-invariant shape canonicalization to identify structurally distinct land regions.
Grid Land Regions: Total Count and Unique Footprints
You are given a 2D grid where each cell holds either 1 (land) or 0 (water). Land cells that touch horizontally or vertically form a region. Diagonal contact does not count.
Your task is to compute two numbers and return them together as a two-element list:
- Total regions — how many distinct connected land regions exist in the grid.
- Unique footprints — how many of those regions have a different shape. Two regions share a shape if you can slide one across the grid (translation only — no rotation, no reflection) and make it sit exactly on top of the other.
Return Format
[total_regions, unique_footprints]
Both values are 0 when the grid is entirely water or empty.
Constraints
0 <= m, n <= 300wheremis the number of rows andnthe number of columns.- Each cell is
0or1(integer). - The grid may be empty (
[]or[[]]), in which case return[0, 0]. - Two regions are the same shape only under translation. Rotations and reflections produce different shapes.
- Diagonal neighbors are not connected.
- Use an iterative traversal strategy — recursive DFS will hit Python's stack limit on large all-land grids.
Examples
Example 1
Input: count_regions_and_footprints([[1, 1, 1, 1, 0], [1, 1, 0, 1, 0], [1, 1, 0, 0, 0], [0, 0, 0, 0, 0]])
Output: [1, 1]
Example 2
Input: count_regions_and_footprints([[1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [0, 0, 0, 1, 1], [0, 0, 0, 1, 1]])
Output: [2, 1]
Example 3
Input: count_regions_and_footprints([[1, 0, 0, 1, 0], [1, 1, 0, 1, 1], [0, 0, 0, 0, 0], [1, 1, 1, 0, 0]])
Output: [3, 2]
Example 4
Input: count_regions_and_footprints([[0, 0, 0], [0, 0, 0], [0, 0, 0]])
Output: [0, 0]
Hints
Hint 1
Scan the grid row by row. Each time you land on an unvisited land cell, you've found a new region — use an iterative stack or queue to visit every cell in that region before moving on.
Hint 2
To fingerprint a region's shape, record each cell's position relative to a fixed anchor point. The anchor should be the first cell you encounter for that region in row-major order (topmost, then leftmost). Relative offsets don't change when the region is shifted, so two translated copies produce identical fingerprints.
Hint 3
Collect all the relative offsets for a region into a sorted tuple, then add it to a set. The final size of that set is your unique-footprint count. Make sure cells are marked visited when they are pushed onto the stack, not when they are popped, to avoid processing the same cell twice.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Part 1 — Counting total regions
Treat the grid as an implicit graph: each land cell is a node, and edges connect horizontally or vertically adjacent land cells. Counting regions is then counting connected components.
Scan every cell in row-major order. When you hit a land cell that hasn't been visited yet, you've found a new component. Increment the counter and flood-fill the entire component iteratively (using an explicit stack), marking every reachable land cell as visited. Because cells are marked visited the moment they are pushed — not when they are popped — no cell enters the stack more than once, which keeps the work proportional to the grid size.
Part 2 — Counting unique footprints
Two regions have the same shape if and only if one is a pure translation of the other. A translation shifts every cell by the same (dr, dc) offset, so relative positions between cells are preserved.
The trick is to define a canonical, translation-invariant signature for each region:
- The anchor is the first cell encountered during the row-major scan — guaranteed to be the topmost, then leftmost cell of that region.
- Express every other cell in the region as
(row - anchor_row, col - anchor_col). - Sort those offsets and pack them into a tuple.
Because any translated copy of the region has its own topmost-leftmost cell, and translation preserves relative positions, both copies produce identical sorted offset tuples. The converse holds too: equal offset sets mean the regions differ only by a shift. Storing these tuples in a Python set deduplicates by shape, and the set's final size is the answer.
Why the anchor is consistent
For two translated copies A and B, the row-major scan always reaches the topmost-leftmost cell of each copy first. Translation preserves the "topmost-leftmost" property: if cell p is the anchor of A, then p + offset is the anchor of B. All other relative offsets within B are identical to those within A, so the signatures match.
Edge cases
- Empty grid or all-water grid →
[0, 0]. - All land → one region, one unique shape.
[[1,0],[0,1]]→ two regions, each a single cell, so one unique shape.- Diagonal neighbors are ignored throughout.
Complexity
| Time | Space | |
|---|---|---|
| Total regions | O(m · n) | O(m · n) |
| Unique footprints | O(m · n · log(m · n)) — sorting per region | O(m · n) — visited set + stored shapes |
The dominant cost is sorting each region's offset list; across all regions the total number of cells is m · n, and sorting costs O(k log k) per region of size k. Using a frozenset instead of a sorted tuple would reduce expected time to O(m · n) at the cost of slightly higher constant factors.
Reference solution
from typing import List
def count_regions_and_footprints(grid: List[List[int]]) -> List[int]:
if not grid or not grid[0]:
return [0, 0]
rows, cols = len(grid), len(grid[0])
visited = set()
shapes = set()
total = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] not in (1, "1") or (r, c) in visited:
continue
# New unvisited land cell — start a new region.
total += 1
stack = [(r, c)]
visited.add((r, c))
cells = []
while stack:
cr, cc = stack.pop()
cells.append((cr, cc))
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = cr + dr, cc + dc
if (
0 <= nr < rows
and 0 <= nc < cols
and grid[nr][nc] in (1, "1")
and (nr, nc) not in visited
):
visited.add((nr, nc))
stack.append((nr, nc))
# The first cell collected is the anchor (topmost-leftmost in
# row-major order). Express every cell as an offset from it.
base_r, base_c = cells[0]
shape = tuple(sorted((cr - base_r, cc - base_c) for cr, cc in cells))
shapes.add(shape)
return [total, len(shapes)]