Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Share a BFS version```from typing import Listfrom collections import dequeclass ...

Victor An

Nov 21, 2022

Share a BFS version


from typing import List
from collections import deque


class Solution:

def numDistinctIslands(self, grid: List[List[int]]) -> int:
self.rows = len(grid)
self.cols = len(grid[0])
self.directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]

island_pattern_set = set()

for x in range(self.rows):
for y in range(self.cols):
if grid[x][y] ==  1:
island_pattern = self.getIslandPattern(grid, x, y)
island_pattern_set.add(tuple(island_pattern))

return len(island_pattern_set)

def getIslandPattern(self, grid, ox, oy):
# BFS
island_pattern = list()
neighbors = deque()
neighbors.append((ox, oy))
while neighbors:
x, y = neighbors.popleft()
# add relative position to the pattern
island_pattern.append((x - ox, y - oy))
grid[x][y] = 0 # mark visited
for ix, iy in self.directions:
nx, ny = x + ix, y + iy
if 0

0

0

Comments
Comments

On this page