Find the number of distinct Islands OR connected components.

Objective: Given a 2d grid map of ‘1’s (land) and ‘0’s (water), count the number of distinct or unique islands.

Island: An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. Assume all four edges of the grid are all surrounded by water. Given such a grid, write an algorithm to find the number of distinct islands in it.

This problem can also be also as find the number of distinct or unique connected components in the given graph.

Example:

Example 1:
Input:
11110
11010
11000
00000
No of distinct Islands: 1

Example 2:
Input:
11000
11011
00100
00011
No of distinct Islands: 2

Example 3:
Input:
11011
10100
00110
10000
11011
No of distinct Islands: 3

Approach:

Earlier we have seen the problem – Find the number of islands. In that problem, the objective was to find the total number of islands in the grid. Finding distinct islands can be considered an extension of that problem. We will use the same approach with some modifications.

Use Depth-First Search

If all the nodes in the grid are connected then after DFS all the nodes will be visited and there will be only one Island in the grid. If there are more islands in the grid we need to multiple DFS to visit them all. So Number of Islands will be equal to the number of DFS required to visit all isLands (1’s)

How to determine if two islands are identical: If coordinates in two islands form an identical shape or structure. The coordinates of both the islands can be at a different location. See the example below 

Steps:

  1. Start the DFS from the node with value 1 (consider this node as start node of the island, store its coordinates in (start_x, start_y)) will be  and try all four directions (right, left, up and down) to find any connected node with 1’s (let’s say connected node coordinates are (x, y)). Calculate its new coordinates with reference to start node as new_x = x-start_x, new_y=y-start_y and store it in list. Once DFS is completed, means we have found an island and all the calculated coordinates are stored in the list. 
  2. Start another DFS from an unvisited node with value 1 (if exists) and once this DFS is completed, coordinates for this island will be stored in the separate list.
  3. Put all these lists into Set, this will remove the duplicates and will have unique islands in the Set.
  4. Once all the nodes are visited, the size of Set will be our answer. (distinct islands). 

Complete Code:

Output

No of unique distinct islands are: 3

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

You may also like...

%d bloggers like this: