Tutorialspoint
Problem
Solution
Submissions

Number of Distinct Islands

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 12

Write a C++ program to count the number of distinct islands in a 2D grid. An island is a group of 1's (representing land) connected horizontally or vertically. Two islands are considered to be the same if and only if one island can be translated (not rotated or reflected) to equal the other. Return the number of distinct islands.

Example 1
  • Input: grid = [[1,1,0,0,0],[1,1,0,0,0],[0,0,0,1,1],[0,0,0,1,1]]
  • Output: 1
  • Explanation:
    • There are two islands, but they are the same shape (both 2x2 squares).
    • Since they have the same shape, we count them as one distinct island.
Example 2
  • Input: grid = [[1,1,0,1,1],[1,0,0,0,0],[0,0,0,0,1],[1,1,0,1,1]]
  • Output: 3
  • Explanation:
    • The three distinct islands are:
    • - The 'L' shape in the top left
    • - The single cell in the bottom right
    • - The 2x2 square divided across the top right and bottom right
Constraints
  • 1 ≤ grid.length, grid[0].length ≤ 50
  • grid[i][j] is either 0 or 1
  • Time Complexity: O(m * n) where m is number of rows and n is number of columns
  • Space Complexity: O(m * n)
ArraysSetCognizanteBay
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use DFS to identify and explore each island
  • Create a unique signature for each island based on relative coordinates
  • Count the number of unique signatures
  • Use a set or hash map to store and count unique island patterns
  • Make sure the signature is normalized to allow for translation

Steps to solve by this approach:

 Step 1: Make a copy of the input grid to avoid modifying the original.
 Step 2: Iterate through each cell in the grid.
 Step 3: When a land cell (1) is found, start a DFS to explore the entire island.
 Step 4: During DFS, create a path signature that represents the shape of the island.
 Step 5: The path records the directions taken during exploration, which captures the island's shape.
 Step 6: Add each unique path to a set to count distinct island shapes.
 Step 7: Return the size of the set as the number of distinct islands.

Submitted Code :