Number of Distinct Islands II - Problem
You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical). You may assume all four edges of the grid are surrounded by water.
An island is considered to be the same as another if they have the same shape, or have the same shape after rotation (90, 180, or 270 degrees only) or reflection (left/right direction or up/down direction).
Return the number of distinct islands.
Input & Output
Example 1 — Basic Grid with Two Distinct Islands
$
Input:
grid = [[1,1,0],[0,1,1],[0,0,0],[1,1,1],[0,1,0]]
›
Output:
2
💡 Note:
First island is L-shaped at positions (0,0), (0,1), (1,1). Second island is T-shaped at positions (3,0), (3,1), (3,2), (4,1). These are different shapes even after all rotations and reflections.
Example 2 — Same Shape Different Orientations
$
Input:
grid = [[1,1,0,0],[1,0,0,1],[0,0,0,1],[0,0,0,1]]
›
Output:
1
💡 Note:
First island: L-shape at (0,0), (0,1), (1,0). Second island: vertical line at (1,3), (2,3), (3,3). The L can be rotated 90° clockwise to become a vertical line, so they're the same shape.
Example 3 — Single Cell Islands
$
Input:
grid = [[1,0,0],[0,1,0],[0,0,1]]
›
Output:
1
💡 Note:
All three islands are single cells. All single-cell islands have the same shape regardless of position, so there's only 1 distinct shape.
Constraints
- 1 ≤ m, n ≤ 50
- grid[i][j] is either 0 or 1
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code