Solution: Number of Distinct Islands
Let’s solve the Number of Distinct Islands problem using the Hash Maps pattern.
We'll cover the following
Statement
Given an m x n
binary matrix where
Constraints:
m
==grid.length
n
==grid[i].length
m
,n
grid[i][j]
is eitheror .
Solution
This algorithm is designed to find the number of distinct islands in a grid, where each island is a group of connected
Here’s the step-by-step implementation of the solution:
Initialize a set to track visited land cells and a dictionary to store the shapes of islands.
Loop through every cell in the grid. For each unvisited cell containing
: Call DFS on the cell.
Explore all connected land cells recursively in all four directions (up, down, left, right) until the entire island is mapped.
Normalize every land cell included in an island by subtracting the coordinates of that land cell from the coordinates of the first cell in the respective island.
Once DFS completes exploring an island, the shape is stored in the dictionary. The key in this dictionary represents the shape, and the value is a count of the islands having the same shape.
After processing the entire grid, return the dictionary as the number of distinct island shapes is the number of unique keys in the dictionary.
Let’s look at the following illustration to get a better understanding of the solution:
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.