This problem asks to find the number of distinct islands in a binary matrix, considering rotations and reflections as equivalent shapes. The solution involves Depth-First Search (DFS) to identify islands, and a normalization technique to handle shape equivalence.
Approach:
Island Identification (DFS): The solution uses DFS to traverse each connected component of 1s (representing land) in the grid. For each island, it records the relative coordinates of the cells within the island relative to the starting cell. This creates a shape representation for each island.
Shape Normalization: The crucial part is to normalize the shapes to account for rotations and reflections. The algorithm generates all eight possible transformations (4 rotations and 4 reflections) of a given island shape. It then sorts these transformations lexicographically, selecting the lexicographically smallest one as the canonical representation. This ensures that islands with the same shape, regardless of orientation, will have the same normalized representation.
Distinct Island Counting: The normalized shapes are stored in a set
(in Python, Java, and C++) to automatically remove duplicates. The final count of unique shapes in the set gives the number of distinct islands.
Time Complexity Analysis:
Therefore, the overall time complexity is dominated by the DFS and normalization steps, resulting in O(MN log(MN)) time complexity.
Space Complexity Analysis:
Hence, the overall space complexity is O(M*N).
Code Examples (with detailed comments):
The provided code snippets in Python, Java, and C++ implement the above approach. The key functions are dfs
(for DFS traversal), normalize
(for shape normalization), and the main function (numDistinctIslands2
) to orchestrate the process. The normalization functions handle the generation of all possible transformations and the sorting to achieve unique representation of island shapes. The use of sets efficiently handles the deduplication of normalized shapes.