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.
Time & Space Complexity
Time Complexity
O(N ร K)
N grid cells visited once, K operations per island cell for transformations
โ Linear Growth
Space Complexity
O(N)
Hash set stores at most N/4 islands (worst case all single cells)
โ Linear Space
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