nathanwailes

LeetCode 417 - Pacific Atlantic Water Flow - 2023.01.03 solution

Jan 3rd, 2023
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.03 KB | None | 0 0
  1. class Solution:
  2.     def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
  3.         """ How to solve it: Iterate through each cell of the four board edges.
  4.        For each cell on a given ocean border, run DFS to find all cells that can flow
  5.        to it.  Add those positions to a can_reach_pacific (or atlantic) set.
  6.        Then just return the intersection of the two sets.
  7.        """
  8.         ROWS = len(heights)
  9.         COLS = len(heights[0])
  10.  
  11.         top_row = [(0, i) for i in range(COLS)]
  12.         left_col = [(i, 0) for i in range(ROWS)]
  13.         bottom_row = [(ROWS-1, i) for i in range(COLS)]
  14.         right_col = [(i, COLS-1) for i in range(ROWS)]
  15.  
  16.         can_reach_pacific = set(top_row + left_col)
  17.         can_reach_atlantic = set(right_col + bottom_row)
  18.  
  19.         def add_neighbors_to_set(p, set_to_use):
  20.             print('add_neighbors_to_set: {}'.format(p))
  21.             mov_dirs = [
  22.                 [0, 1],
  23.                 [0, -1],
  24.                 [1, 0],
  25.                 [-1, 0],
  26.             ]
  27.             neighbors = [(p[0] + d[0], p[1] + d[1]) for d in mov_dirs]
  28.             for neighbor in neighbors:
  29.                 if neighbor[0] < 0 or neighbor[0] >= ROWS or \
  30.                    neighbor[1] < 0 or neighbor[1] >= COLS or \
  31.                    heights[neighbor[0]][neighbor[1]] < heights[p[0]][p[1]] or \
  32.                    neighbor in set_to_use:
  33.                    continue
  34.                 else:
  35.                     set_to_use.add(neighbor)
  36.                     add_neighbors_to_set(neighbor, set_to_use)
  37.         print('add_neighbors_to_set for pacific')
  38.         for pos in top_row + left_col:
  39.             print('for loop: {}'.format(pos))
  40.             add_neighbors_to_set(pos, can_reach_pacific)
  41.         print('add_neighbors_to_set for atlantic')
  42.         for pos in bottom_row + right_col:
  43.             print('for loop: {}'.format(pos))
  44.             add_neighbors_to_set(pos, can_reach_atlantic)
  45.         # print(': {}'.format())
  46.         return can_reach_pacific.intersection(can_reach_atlantic)
Advertisement
Add Comment
Please, Sign In to add comment