KatInterview

Grid Land Regions: Total Count and Unique Footprints

Trees & GraphsAuto-graded · 28 test cases
MediumAuto-gradedTrees & Graphsgraph traversalflood fillconnected components

Last 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:

  1. Total regions — how many distinct connected land regions exist in the grid.
  2. 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 <= 300 where m is the number of rows and n the number of columns.
  • Each cell is 0 or 1 (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.