Practice/Oracle/Leetcode 694. Number of Distinct Islands
CodingMust
You are given a 2D binary grid where each cell contains either 0 (water) or 1 (land). An island is defined as a group of adjacent land cells connected horizontally or vertically (4-directional connectivity).
Your task is to count how many distinct island shapes exist in the grid. Two islands are considered to have the same shape if one can be translated (shifted) to match the other exactly. Rotation and reflection do not count as the same shape.
For example, these two islands have the same shape because the second is just a translation of the first:
Island 1: Island 2: 1 1 1 1 1 1
But these two islands have different shapes:
Island 1: Island 2: 1 1 1 1 1 1
1 <= grid.length, grid[0].length <= 50grid[i][j] is either 0 or 1Example 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 both form a 2×2 square shape. When normalized to start from the same origin point, they are identical.
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: There are four islands with three distinct shapes that cannot be translated to match each other.
Example 3:
Input: grid = [ [1,0,1], [0,0,0], [1,0,1] ] Output: 1 Explanation: All four islands are single cells, representing the same shape.