Number of Distinct Islands II Problem
Description
LeetCode Problem 711.
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.
Example 1:

Input: grid = [[1,1,0,0,0],[1,0,0,0,0],[0,0,0,0,1],[0,0,0,1,1]]
Output: 1
Explanation: The two islands are considered the same because if we make a 180 degrees clockwise rotation on the first island, then two islands will have the same shapes.
Example 2:

Input: grid = [[1,1,0,0,0],[1,1,0,0,0],[0,0,0,1,1],[0,0,0,1,1]]
Output: 1
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 50grid[i][j]is either0or1.
Solution
Approach: Canonical Shape over the 8 Transformations
Now two islands count as the same if one is a rotation or reflection of the other. A shape has at most 8 such versions (4 rotations, each of them either mirrored or not). Every version can be written as a transform of each cell (r, c):
(r, c), (r, -c), (-r, c), (-r, -c), (c, r), (c, -r), (-c, r), (-c, -r)
For each island:
- Collect its cells with a DFS (an explicit stack avoids deep recursion), marking them visited.
- For each of the 8 transforms, apply it to all cells. Then shift the result so its smallest row and smallest column are
0, which removes the island's position. Sort the cells and turn them into a key, such as the list ofrow * 64 + colcodes. Sorting makes the key independent of the order in which the DFS found the cells. - Keep the smallest of the 8 keys. This is the island's canonical form: every rotated or mirrored copy of the same shape has the same 8 versions, so it picks the same smallest key.
Count the distinct canonical keys with a set. Both the shift and the sort are needed. Without the shift, the same shape in a different place gets a different key. Without the sort, the same shape explored in a different order gets a different key.
Complexity: O(m · n · log(m · n)) time, from sorting 8 versions of each island; O(m · n) extra space.
class Solution:
def numDistinctIslands2(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
def cells_of(i, j):
"""All cells of the island at (i, j); marks them visited."""
grid[i][j] = 0
stack, cells = [(i, j)], []
while stack:
r, c = stack.pop()
cells.append((r, c))
for x, y in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= x < m and 0 <= y < n and grid[x][y] == 1:
grid[x][y] = 0
stack.append((x, y))
return cells
def canonical(cells):
"""The same key for all 8 rotations and reflections of a shape."""
keys = []
for t in range(8):
pts = []
for r, c in cells:
x, y = (r, c) if t < 4 else (c, r) # t >= 4: swap the axes
if t & 1:
y = -y
if t & 2:
x = -x
pts.append((x, y))
# Move the shape so its smallest row and column are 0, then list its cells in order.
min_x = min(x for x, _ in pts)
min_y = min(y for _, y in pts)
codes = sorted((x - min_x) * 64 + (y - min_y) for x, y in pts)
keys.append(",".join(map(str, codes)))
return min(keys)
shapes = set()
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
shapes.add(canonical(cells_of(i, j)))
return len(shapes)