Number of Distinct Islands II - Problem
You are given an m × n binary matrix grid where 1 represents land and 0 represents water. Islands are formed by connecting adjacent land cells (horizontally or vertically).
Here's the twist: islands are considered identical if they have the same shape, even after applying transformations like:
- 🔄 Rotations: 90°, 180°, or 270° clockwise
- 🪞 Reflections: horizontal (left-right) or vertical (up-down)
Your task is to count how many truly distinct island shapes exist in the grid.
Example: An L-shaped island is the same as its rotated or reflected versions, so they should count as one distinct island.
Input & Output
example_1.py — Basic Island Shapes
$
Input:
grid = [[1,1,0],[0,1,1],[0,0,0],[1,1,1]]
›
Output:
1
💡 Note:
The top island (L-shape) and bottom island (straight line) are different when considering rotations and reflections. However, after transformations, they represent different canonical forms, resulting in 2 distinct islands.
example_2.py — Identical After Rotation
$
Input:
grid = [[1,1],[1,0],[0,1]]
›
Output:
1
💡 Note:
Even though there might appear to be different shapes, when we consider all possible rotations and reflections, some islands become identical to others, resulting in fewer distinct shapes.
example_3.py — Single Cells
$
Input:
grid = [[1,0,1],[0,0,0],[1,0,1]]
›
Output:
1
💡 Note:
All single-cell islands are identical regardless of position, so they count as one distinct island shape.
Constraints
- m == grid.length
- n == grid[i].length
- 1 ≤ m, n ≤ 50
-
grid[i][j] is either
0or1 - The number of islands is at most min(m×n, 50)
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code