You are given an m x n binary matrix grid. An island is a group of 1s (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.
Function Signature
def num_distinct_islands(grid: list[list[int]]) -> int:
...
Rules
-
Two land cells are connected only when they share an edge (up, down, left or right). Diagonal neighbors are not connected.
-
Two islands have the same shape when shifting one of them horizontally and vertically makes it match the other cell for cell. A rotated or mirrored copy is a different shape.
-
Return
0
when the grid has no land.
Constraints
-
m == grid.length
-
n == grid[i].length
-
1 <= m, n <= 50
-
grid[i][j]
is either
0
or
1
.
Examples
Input: grid = [
[1,1,0,0,0],
[1,1,0,0,0],
[0,0,0,1,1],
[0,0,0,1,1]
]
Output: 1
There are two islands, and both are 2x2 squares. They have the same shape, so the answer is 1.
Input: grid = [
[1,1,0,1,1],
[1,0,0,0,0],
[0,0,0,0,1],
[1,1,0,1,1]
]
Output: 3
The four islands are an L at the top left (cells (0,0), (0,1), (1,0)), a horizontal pair at the top right, another L at the bottom right (cells (2,4), (3,3), (3,4)) and a horizontal pair at the bottom left. The two pairs match by translation, while the two Ls are 180-degree rotations of each other and count separately, which gives 3 shapes.
Input: grid = [
[1,0,1],
[0,1,0]
]
Output: 1
The three land cells touch only diagonally, so they form three single-cell islands. All of them have the same shape.