Approach
Depth-first search
For Number of Distinct Islands II, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 53 lines of Python from the credited upstream file 711.py.
- The implementation visibly relies on sequence storage, ordered lookup.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def numDistinctIslands2(self, grid: list[list[int]]) -> int:3 seen = set()4 5 def dfs(i: int, j: int):6 if i < 0 or i == len(grid) or j < 0 or j == len(grid[0]):7 return8 if grid[i][j] == 0 or (i, j) in seen:9 return10 11 seen.add((i, j))12 island.append((i, j))13 dfs(i + 1, j)14 dfs(i - 1, j)15 dfs(i, j + 1)16 dfs(i, j - 1)17 18 def normalize(island: list[tuple]) -> list[tuple]:19 20 points = [[] for _ in range(8)]21 22 for i, j in island:23 points[0].append((i, j))24 points[1].append((i, -j))25 points[2].append((-i, j))26 points[3].append((-i, -j))27 points[4].append((j, i))28 points[5].append((j, -i))29 points[6].append((-j, i))30 points[7].append((-j, -i))31 32 points = [sorted(p) for p in points]33 34 35 for p in points:36 for i in range(1, len(island)):37 p[i] = (p[i][0] - p[0][0],38 p[i][1] - p[0][1])39 p[0] = (0, 0)40 41 return sorted(points)[0]42 43 islands = set() 44 45 for i in range(len(grid)):46 for j in range(len(grid[0])):47 island = []48 dfs(i, j)49 if island:50 islands.add(frozenset(normalize(island)))51 52 return len(islands)53