Number of Distinct Islands Problem
Description
LeetCode Problem 694.
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 and only if one island can be translated (and not rotated or reflected) to equal the other.
Return the number of distinct islands.
Example 1:

Input: grid = [[1,1,0,0,0],[1,1,0,0,0],[0,0,0,1,1],[0,0,0,1,1]]
Output: 1
Example 2:

Input: grid = [[1,1,0,1,1],[1,0,0,0,0],[0,0,0,0,1],[1,1,0,1,1]]
Output: 3
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 50grid[i][j]is either0or1.
Solution
Approach: DFS Path Signature
Two islands are the same when one can be moved onto the other without rotating it. We need a key for each island that does not depend on where the island is.
Explore each island with a DFS that always starts at its first cell in row-major order (the top-left-most cell we meet while scanning) and always tries the four directions in the same order. Record the path as a string: a letter for each step (D, U, R, L), and a B each time the DFS backs up from a cell. Two islands with the same shape produce the same DFS run, so they get the same string. Islands with different shapes get different strings. Mark cells as visited by setting them to 0.
The back-up marks are needed. Without them, different shapes can give the same string. For example, a right step then a down step could mean "down from the second cell" or "down from the first cell after going back", and those are different shapes. The B shows exactly where each branch of the DFS ends.
Put every island's string in a set; the answer is the size of the set.
Complexity: O(m · n) time and O(m · n) extra space for the strings and the recursion.
class Solution:
def numDistinctIslands(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
moves = ((1, 0, "D"), (-1, 0, "U"), (0, 1, "R"), (0, -1, "L"))
def dfs(i, j, path):
grid[i][j] = 0 # mark as visited
for di, dj, step in moves:
x, y = i + di, j + dj
if 0 <= x < m and 0 <= y < n and grid[x][y] == 1:
path.append(step)
dfs(x, y, path)
path.append("B") # back to (i, j)
shapes = set()
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
path = ["S"]
dfs(i, j, path)
shapes.add("".join(path))
return len(shapes)