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.
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.
Input: grid = [[1,0,1],[0,0,0],[1,0,1]] Output: 1 Four single-cell islands, all the same shape.
- 1 <= R, C <= 500 - grid[i][j] is 0 or 1
Counting islands is easy; the twist is treating same-shape islands as one. The fix is to give each island a translation-invariant signature and count distinct signatures.
Two clean signatures:
D/U/R/L) plus a backtrack marker B. The traversal shape — not the absolute position — is captured, and the backtrack markers keep different shapes from colliding.Either way, drop the signature into a set and return its size. O(R·C).
“Are rotations/reflections the same shape?”
No — only translations count as the same.
“4- or 8-directional?”
4-directional.
I flood each island and build a translation-invariant signature — relative offsets from the first cell, or a DFS move-string.
I add each signature to a set and return its size.
Worked example — two L-shaped islands in different corners
both flood to offsets {(0,0),(1,0),(1,1)} -> same signature -> counted once
Offsets from the first cell are identical for translated shapes.
Without them, different DFS shapes can produce the same move string.
The answer is the number of unique fingerprints.
| Relative coordinates | DFS path signature | |
|---|---|---|
| Signature | offset set from the anchor | move string with backtracks |
| Time | O(R·C log) | O(R·C) |
| Idea | position-free coordinates | position-free traversal |
Both group translated islands together and count the distinct groups. Full code is in the Approaches selector below.
Key takeaway
Give each island a translation-invariant signature — relative offsets from its anchor, or a DFS move string with backtrack markers — and count the distinct signatures. O(R·C).
for each island: sig = shape fingerprint; shapes.add(sig) answer = len(shapes)