VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-number-of-distinct-islands-in-a-2d-matrix/

⇱ Find the number of distinct islands in a 2D matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find the number of distinct islands in a 2D matrix

Last Updated : 11 Jul, 2025

Given a boolean 2D matrix. The task is to find the number of distinct islands where a group of connected 1s (horizontally or vertically) forms an island. Two islands are considered to be distinct if and only if one island is not equal to another (not rotated or reflected).

Examples:

Input: grid[][] = 
{{1, 1, 0, 0, 0}, 
1, 1, 0, 0, 0}, 
0, 0, 0, 1, 1}, 
0, 0, 0, 1, 1}}
Output:
Island 1, 1 at the top left corner is same as island 1, 1 at the bottom right corner
Input: grid[][] = 
{{1, 1, 0, 1, 1}, 
1, 0, 0, 0, 0}, 
0, 0, 0, 0, 1}, 
1, 1, 0, 1, 1}}
Output:

Distinct islands in the example above are 1, 1 at the top left corner; 1, 1 at the top right corner and 1 at the bottom right corner. We ignore the island 1, 1 at the bottom left corner since 1, 1 it is identical to the top right corner.


Approach: This problem is an extension of the problem Number of Islands.

The core of the question is to know if 2 islands are equal. The primary criteria is that the number of 1's should be same in both. But this cannot be the only criteria as we have seen in example 2 above. So how do we know? We could use the position/coordinates of the 1's. 
If we take the first coordinates of any island as a base point and then compute the coordinates of other points from the base point, we can eliminate duplicates to get the distinct count of islands. So, using this approach, the coordinates for the 2 islands in example 1 above can be represented as: [(0, 0), (0, 1), (1, 0), (1, 1)].

Below is the implementation of the above approach: 


Output
Number of distinct islands is 3

Time complexity: O(rows * cols * log(rows * cols))

Where rows is the number of rows and cols is the number of columns in the matrix, here we visit every cell so O(row * col) for that and for every cell we need to add atmost (row * col) pairs in set which will cost us O(log(rows*cols)) so overall time complexity will be O(rows * cols * log(rows * cols)) 

Auxiliary Space: O(rows * cols) 

In set we need to ad atmost rows*cols entry so space complexity will be O(rows * cols)

Comment
Article Tags: