
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)
Editorial
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. |
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