Number of distinct islands

Graphs Traversal Problems Medium

Given a boolean 2D matrix grid of size N x M. 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 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: 1

Explanation:


Same colored islands are equal. We have 2 equal islands, so we have only 1 distinct island.

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:

Same colored islands are equal. We have 4 islands, but 2 of them are equal, So we have 3 distinct islands..

Input: grid = [[1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [0, 0, 0, 0, 0],[0, 0, 0, 1, 1]]

Constraints

  •   1 <= N, M <= 500
  •   grid[i][j] == 0 or 1

Company Tags

PayPal Cerner Bain & Company MongoDB Flipkart Johnson & Johnson Oracle Alibaba Pinterest Mastercard Instacart NVIDIA Optum Ernst & Young Wayfair DoorDash eBay Splunk Qualcomm Etsy Siemens Healthineers Zoho Square Dropbox Rockstar Games Google Microsoft Amazon Meta Apple Netflix Adobe