665. Distinct Island Shapes
A strategy game stores its terrain in the grid grid, with 1 for land and 0 for water. An island is a maximal group of land cells joined up, down, left or right. Two islands have the same shape when one of them can be slid onto the other by a pure shift, with no rotation and no mirroring; a pair of islands that are mirror images or turned by a quarter turn counts as two different shapes unless they also match by shifting alone.
Return the number of different shapes among all islands of the grid, or 0 if there is no land. The grid may hold well over a hundred thousand cells, so avoid comparing every pair of islands: describe each island by a position-independent signature and count the distinct signatures.
Example 1
- Input:
- grid = [[1,1,0,0,1],[1,0,0,0,1],[0,0,0,1,1],[1,1,0,1,0]]
- Output:
- 3
- Explanation:
There are three islands: a three-cell corner at the top left, a five-cell winding strip on the right and a two-cell horizontal bar at the bottom left, and no two of them match, so the answer is 3.
Example 2
- Input:
- grid = [[1,0,1,0,1],[1,0,1,0,1]]
- Output:
- 1
- Explanation:
Three vertical bars of height 2 are separated by water; they are all shifted copies of one shape, so the answer is 1.
Example 3
- Input:
- grid = [[1,1,0,0,0],[0,1,0,1,1],[0,0,0,1,0]]
- Output:
- 2
- Explanation:
Both islands have three cells in an L-shape, but one is the mirror image of the other and mirrors do not count as equal, so the answer is 2.
Constraints
1 ≤ rows, cols ≤ 400
each cell is 0 or 1
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 600 msC++ 150 msJava 300 msJavaScript 300 msTypeScript 300 ms
Expected complexity
- Time
- O(rows*cols)
- Space
- O(rows*cols)