You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical). You may assume all four edges of the grid are surrounded by water.

An island is considered to be the same as another if they have the same shape, or have the same shape after rotation (90, 180, or 270 degrees only) or reflection (left/right direction or up/down direction).

Return the number of distinct islands.

Input & Output

Example 1 — Basic Grid with Two Distinct Islands
$ Input: grid = [[1,1,0],[0,1,1],[0,0,0],[1,1,1],[0,1,0]]
Output: 2
💡 Note: First island is L-shaped at positions (0,0), (0,1), (1,1). Second island is T-shaped at positions (3,0), (3,1), (3,2), (4,1). These are different shapes even after all rotations and reflections.
Example 2 — Same Shape Different Orientations
$ Input: grid = [[1,1,0,0],[1,0,0,1],[0,0,0,1],[0,0,0,1]]
Output: 1
💡 Note: First island: L-shape at (0,0), (0,1), (1,0). Second island: vertical line at (1,3), (2,3), (3,3). The L can be rotated 90° clockwise to become a vertical line, so they're the same shape.
Example 3 — Single Cell Islands
$ Input: grid = [[1,0,0],[0,1,0],[0,0,1]]
Output: 1
💡 Note: All three islands are single cells. All single-cell islands have the same shape regardless of position, so there's only 1 distinct shape.

Constraints

  • 1 ≤ m, n ≤ 50
  • grid[i][j] is either 0 or 1

Visualization

Tap to expand
INPUT GRIDIsland 1: L-shapedIsland 2: T-shapedBinary matrix withconnected componentsFind all islands using DFSALGORITHM1Extract Islands with DFS2Generate 8 Transformations4 rotations × 2 reflections3Normalize to CanonicalTranslate to origin + sort points4Hash Set for UniquenessStore canonical formsTransformation Example:L-shape → Rotate 90° → |Different from T-shapeRESULT2Distinct IslandsIsland 1: L-shapedIsland 2: T-shapedAfter all transformations,these remain uniqueHash Set Contents:"0,0|0,1|1,0" (L-shape canonical)"0,0|0,1|0,2|1,1" (T-shape canonical)Two unique shapes foundKey Insight:Islands are the same if any rotation or reflection makes them identical.Generate all 8 transformations and use canonical forms for comparison.TutorialsPoint - Number of Distinct Islands II | DFS with Shape Normalization
Asked in
Google 35 Amazon 25 Facebook 20 Microsoft 15
32.0K Views
Medium Frequency
~35 min Avg. Time
845 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