Problem Description
Given an m x n binary matrix grid, an island is a group of 1's (lands) connected 4-directionally (horizontally or vertically). All four edges of the grid are surrounded by water (0's). Two islands are considered the same if one island can be translated (shifted) to coincide exactly with the other – rotations and reflections are not allowed. The task is to return the number of distinct islands.
Key Insights
- Use DFS/BFS to traverse and mark each island.
- For each island, record its shape relative to a starting coordinate to allow translation invariance.
- Represent the island's shape as a unique signature (e.g., tuple or string of relative positions).
- Use a set (or hash table) to store unique shapes.
Space and Time Complexity
Time Complexity: O(m * n) as each cell is visited once. Space Complexity: O(m * n) in the worst-case due to recursion stack and storing island shapes.
Solution
Use depth-first search (DFS) to explore the grid. When an unvisited land cell (1) is encountered, initiate a DFS to traverse the entire island. Record each land cell's coordinates relative to the starting position of the island. This relative representation is invariant under translation, making it possible to compare island shapes. Store the canonical shape signature (for example, as a tuple or string) in a set to ensure uniqueness. Finally, return the size of the set as the number of distinct islands.