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 and only if one island can be translated (and not rotated or reflected) to equal the other.

Return the number of distinct islands.

Input & Output

Example 1 — Basic Islands
$ Input: grid = [[1,1,0,1,1],[1,1,0,1,1],[0,0,0,0,0],[1,1,0,1,1],[1,1,0,1,1]]
Output: 1
💡 Note: The grid has 4 islands total, all with the same 2x2 square shape. When normalized, they all have the same relative coordinates: (0,0), (0,1), (1,0), (1,1). Therefore, there is only 1 distinct island shape.
Example 2 — L-shaped Islands
$ Input: grid = [[1,1,0],[1,0,0],[0,0,1]]
Output: 2
💡 Note: First island is L-shaped at positions (0,0),(0,1),(1,0). Second island is a single cell at (2,2). These are 2 different shapes when normalized.
Example 3 — Single Cell
$ Input: grid = [[1,0,1],[0,0,0],[1,0,1]]
Output: 1
💡 Note: All four islands are single cells at (0,0), (0,2), (2,0), (2,2). They all have the same shape: just one cell at relative position (0,0).

Constraints

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

Visualization

Tap to expand
Number of Distinct Islands INPUT 1 1 0 1 1 1 1 0 1 1 0 0 0 0 0 1 1 0 1 1 1 1 0 1 1 Island A Island B Island C Island D Water 4 islands found in grid m=5, n=5 grid[5][5] binary matrix ALGORITHM STEPS 1 DFS Traversal Find each island using DFS Mark visited cells 2 Path Encoding Record direction: D,U,L,R Relative to start position 3 Normalize Shape Translate to origin (0,0) Create unique signature 4 Store in Set Add path to HashSet Duplicates auto-removed Path Signatures: "DRDB" (2x2 square) "DRDB" (2x2 square) "DRDB" (2x2 square) "DRDB" (2x2 square) FINAL RESULT Distinct Island Shapes: Type 1 2x2 Square Island Count Analysis: Total Islands Found: 4 All are 2x2 squares Same shape = 1 distinct (Only translation differs) Output: 3 3 Distinct Islands Key Insight: Path encoding captures island shape by recording DFS traversal directions (Down, Up, Left, Right, Back). Islands with identical paths have the same shape. Using a HashSet automatically removes duplicates, so the set size equals the count of distinct islands. Time: O(m*n), Space: O(m*n). TutorialsPoint - Number of Distinct Islands | DFS with Path Encoding Approach
Asked in
Google 15 Facebook 12 Amazon 8 Microsoft 6
28.0K Views
Medium Frequency
~25 min Avg. Time
890 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