> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Number of Distinct Islands II Python Solution

> Tested Python solution for LeetCode 711 with 12 pytest cases. Generate a practice environment with lcpy.

LeetCode 711, [Hard](/catalog/hard). Topics: [Hash Table](/catalog/topics/hash-table), [Depth-First Search](/catalog/topics/depth-first-search), [Breadth-First Search](/catalog/topics/breadth-first-search), [Union Find](/catalog/topics/union-find). [View on LeetCode](https://leetcode.com/problems/number-of-distinct-islands-ii/description/).

Generate this problem as a practice environment: tested reference solution, 12 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 711   # by problem number
lcpy gen -s number_of_distinct_islands_ii   # by problem name
```

## Problem

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.

### Examples

```
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.
```

```
Input: grid = [[1,1,0,0,0],[1,1,0,0,0],[0,0,0,1,1],[0,0,0,1,1]]
Output: 1
Explanation: The two islands are considered the same because they are identical.
```

### Constraints

* m == grid.length
* n == grid\[i].length
* 1 \<= m, n \<= 50
* grid\[i]\[j] is either 0 or 1.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/number_of_distinct_islands_ii/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/number_of_distinct_islands_ii/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(m * n * log(m * n))
    # Space: O(m * n)
    def num_distinct_islands_ii(self, grid: list[list[int]]) -> int:
        m, n = len(grid), len(grid[0])
        seen = [[False] * n for _ in range(m)]

        def dfs(i: int, j: int, shape: list[tuple[int, int]]) -> None:
            if not (0 <= i < m and 0 <= j < n) or seen[i][j] or grid[i][j] == 0:
                return
            seen[i][j] = True
            shape.append((i, j))
            for a, b in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                dfs(i + a, j + b, shape)

        def normalize(shape: list[tuple[int, int]]) -> tuple[tuple[int, int], ...]:
            variants: list[list[tuple[int, int]]] = [[] for _ in range(8)]
            for i, j in shape:
                variants[0].append((i, j))
                variants[1].append((i, -j))
                variants[2].append((-i, j))
                variants[3].append((-i, -j))
                variants[4].append((j, i))
                variants[5].append((j, -i))
                variants[6].append((-j, i))
                variants[7].append((-j, -i))
            norm = []
            for e in variants:
                e.sort()
                x0, y0 = e[0]
                norm.append(tuple((x - x0, y - y0) for x, y in e))
            norm.sort()
            return norm[0]

        islands: set[tuple[tuple[int, int], ...]] = set()
        for i in range(m):
            for j in range(n):
                if grid[i][j] and not seen[i][j]:
                    shape: list[tuple[int, int]] = []
                    dfs(i, j, shape)
                    islands.add(normalize(shape))
        return len(islands)
```

## Complexity

| Time | Space |
| - | - |
| O(m \* n \* log(m \* n)) | O(m \* n) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.