Problem Description
Given an m x n binary matrix, an island is defined as a group of connected lands (cells with value 1) connected 4-directionally. Two islands are considered the same if one island can be rotated (90, 180, or 270 degrees) or reflected (horizontally or vertically) to match the other. The objective is to return the number of distinct islands under these transformation rules.
Key Insights
- Use DFS or BFS to traverse and record the coordinates of cells in each island.
- For each island, generate all 8 possible transformations (4 rotations and each can be reflected) and normalize them.
- Convert the normalized coordinates into a canonical representation (for example, a sorted tuple) so that islands with the same shape (up to rotation/reflection) match.
- Store these canonical representations in a set to count distinct islands.
Space and Time Complexity
Time Complexity: O(m * n) where m and n are the grid dimensions. Each island is processed and 8 transformations (a constant factor) are generated. Space Complexity: O(m * n) for recursion stack and storage of island coordinates and canonical shapes.
Solution
We iterate over each cell in the grid. When a cell with a 1 is found, we perform a DFS to capture all the coordinates of the island, marking cells as visited. For each island found, we generate 8 transformations corresponding to all combinations of rotations and reflections. Each transformed set of coordinates is normalized by translating them so that the smallest coordinate becomes (0, 0). We then sort and choose the lexicographically smallest transformation as the canonical representation. A set is used to track distinct canonical forms, and finally the size of this set is returned.