You are given an m ร— n binary matrix grid where 1 represents land and 0 represents water. Islands are formed by connecting adjacent land cells (horizontally or vertically).

Here's the twist: islands are considered identical if they have the same shape, even after applying transformations like:

  • ๐Ÿ”„ Rotations: 90ยฐ, 180ยฐ, or 270ยฐ clockwise
  • ๐Ÿชž Reflections: horizontal (left-right) or vertical (up-down)

Your task is to count how many truly distinct island shapes exist in the grid.

Example: An L-shaped island is the same as its rotated or reflected versions, so they should count as one distinct island.

Input & Output

example_1.py โ€” Basic Island Shapes
$ Input: grid = [[1,1,0],[0,1,1],[0,0,0],[1,1,1]]
โ€บ Output: 1
๐Ÿ’ก Note: The top island (L-shape) and bottom island (straight line) are different when considering rotations and reflections. However, after transformations, they represent different canonical forms, resulting in 2 distinct islands.
example_2.py โ€” Identical After Rotation
$ Input: grid = [[1,1],[1,0],[0,1]]
โ€บ Output: 1
๐Ÿ’ก Note: Even though there might appear to be different shapes, when we consider all possible rotations and reflections, some islands become identical to others, resulting in fewer distinct shapes.
example_3.py โ€” Single Cells
$ Input: grid = [[1,0,1],[0,0,0],[1,0,1]]
โ€บ Output: 1
๐Ÿ’ก Note: All single-cell islands are identical regardless of position, so they count as one distinct island shape.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(N ร— K)

N grid cells visited once, K operations per island cell for transformations

n
2n
โœ“ Linear Growth
Space Complexity
O(N)

Hash set stores at most N/4 islands (worst case all single cells)

n
2n
โœ“ Linear Space

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 โ‰ค m, n โ‰ค 50
  • grid[i][j] is either 0 or 1
  • The number of islands is at most min(mร—n, 50)
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen