Number of distinct islands
class Solution:
def __init__(self):
self.islands = []
self.visited = set()
self.directions = [(0, 1), (0, -1), (-1, 0), (1, 0)]
self.curr = []
def dfs(self, grid, i, j):
for dx, dy in self.directions:
x, y = i + dx, j + dy
if 0 <= x < len(grid) and 0 <= y < len(grid[0]) and grid[x][y] == 1 and (x, y) not in self.visited:
self.visited.add((x, y))
self.curr.append((x, y))
self.dfs(grid, x, y)
def numDistinctIslands(self, grid: List[List[int]]) -> int:
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1 and (i, j) not in self.visited:
self.visited.add((i, j))
self.curr = [(i, j)]
self.dfs(grid, i, j)
self.islands.append(self.curr.copy())
moved = set()
for island in self.islands:
xs = [i[0] for i in island]
ys = [i[1] for i in island]
xmove = min(xs)
ymove = min(ys)
tmp = [(x - xmove, y - ymove) for x,y in island]
moved.add(tuple(tmp))
return len(moved)
Number of Distinct Islands
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.