LeetCode 0694. Number of Distinct Islands Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0694. Number of Distinct Islands

Description

You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

An island is considered to be the same as another if and only if one island can be translated (and not rotated or reflected) to equal the other.

Return the number of distinct islands.

 

Example 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

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

 

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 50
  • grid[i][j] is either 0 or 1.

Solutions

Solution 1

PythonJavaC++GoTypeScript
class Solution: def numDistinctIslands(self, grid: List[List[int]]) -> int: def dfs(i: int, j: int, k: int): grid[i][j] = 0 path.append(str(k)) dirs = (-1, 0, 1, 0, -1) for h in range(1, 5): x, y = i + dirs[h - 1], j + dirs[h] if 0 <= x < m and 0 <= y < n and grid[x][y]: dfs(x, y, h) path.append(str(-k)) paths = set() path = [] m, n = len(grid), len(grid[0]) for i, row in enumerate(grid): for j, x in enumerate(row): if x: dfs(i, j, 0) paths.add("".join(path)) path.clear() return len(paths)(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !