Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution:
- def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
- """ How to solve it: Iterate through each cell of the four board edges.
- For each cell on a given ocean border, run DFS to find all cells that can flow
- to it. Add those positions to a can_reach_pacific (or atlantic) set.
- Then just return the intersection of the two sets.
- """
- ROWS = len(heights)
- COLS = len(heights[0])
- top_row = [(0, i) for i in range(COLS)]
- left_col = [(i, 0) for i in range(ROWS)]
- bottom_row = [(ROWS-1, i) for i in range(COLS)]
- right_col = [(i, COLS-1) for i in range(ROWS)]
- can_reach_pacific = set(top_row + left_col)
- can_reach_atlantic = set(right_col + bottom_row)
- def add_neighbors_to_set(p, set_to_use):
- print('add_neighbors_to_set: {}'.format(p))
- mov_dirs = [
- [0, 1],
- [0, -1],
- [1, 0],
- [-1, 0],
- ]
- neighbors = [(p[0] + d[0], p[1] + d[1]) for d in mov_dirs]
- for neighbor in neighbors:
- if neighbor[0] < 0 or neighbor[0] >= ROWS or \
- neighbor[1] < 0 or neighbor[1] >= COLS or \
- heights[neighbor[0]][neighbor[1]] < heights[p[0]][p[1]] or \
- neighbor in set_to_use:
- continue
- else:
- set_to_use.add(neighbor)
- add_neighbors_to_set(neighbor, set_to_use)
- print('add_neighbors_to_set for pacific')
- for pos in top_row + left_col:
- print('for loop: {}'.format(pos))
- add_neighbors_to_set(pos, can_reach_pacific)
- print('add_neighbors_to_set for atlantic')
- for pos in bottom_row + right_col:
- print('for loop: {}'.format(pos))
- add_neighbors_to_set(pos, can_reach_atlantic)
- # print(': {}'.format())
- return can_reach_pacific.intersection(can_reach_atlantic)
Advertisement
Add Comment
Please, Sign In to add comment