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 ofdistinct islands.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 50
grid[i][j]
is either0
or1
.
Solution
Method 1 – DFS/BFS with Canonical Shape Encoding (Rotation & Reflection)
Intuition
To count distinct islands considering rotation and reflection, we must encode each island’s shape in a way that is invariant to translation, rotation, and reflection. For each island, generate all 8 possible transformations (4 rotations × 2 reflections), normalize each, and use the lexicographically smallest as its canonical form.
Approach
- For each unvisited land cell, start a DFS/BFS and record all coordinates of the island.
- For each island, generate all 8 transformations (rotations and reflections), normalize (shift to origin), and serialize.
- Store the canonical form of each island in a set to ensure uniqueness.
- The answer is the size of the set.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(mn * k log k)
(k = island size) - 🧺 Space complexity:
O(mn)