Number of Distinct Islands

medium

Given an R × C grid of 0s and 1s, an island is a maximal 4-directionally connected group of 1s. Two islands are the same if one can be translated (shifted, without rotation or reflection) to match the other. Return the number of distinct island shapes.

Hints

Two islands are the same if one shifts onto the other — you need a position-independent fingerprint.
Anchor each island at its first cell and record relative offsets.
Alternatively, encode the DFS traversal as a move string with backtrack markers.

Common doubts

Subtracting a fixed reference removes absolute position, so translated islands produce identical offset sets.
Without it, two different shapes can produce the same sequence of moves; the 'B' records when the traversal returns, distinguishing them.
No — only translations. Handling rotations/reflections would require canonicalizing over all 8 transformations.

Interview follow-ups

Generate all 8 transformed signatures of each island and take the lexicographically smallest as the canonical key.
The relative-coordinate set is conceptually simplest; the DFS move string is compact and avoids sorting.

Fun facts

  • LeetCode 694 — the shape-aware sibling of number of islands.
  • The DFS path signature is a form of tree/graph canonical hashing.

Asked at

AmazonGoogleFacebook
Frequently Sometimes Occasionally
Example 1
Input: grid = [[1,1,0,0,0],[1,1,0,0,0],[0,0,0,1,1],[0,0,0,1,1]]
Output: 1
Both islands are 2×2 squares — the same shape.
Example 2
Input: grid = [[1,0,1],[0,0,0],[1,0,1]]
Output: 1
Four single-cell islands, all the same shape.
Constraints

- 1 <= R, C <= 500 - grid[i][j] is 0 or 1

Solve this problem →