Advertisement
smj007

Untitled

Aug 16th, 2023 (edited)
934
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.09 KB | None | 0 0
  1. # DFS solution
  2.  
  3. class Solution:
  4.     def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
  5.  
  6.         n, m = len(heights), len(heights[0])
  7.         result = []
  8.         p_visited = set()
  9.         a_visited = set()
  10.  
  11.         def dfs(r, c, visited):
  12.             if r not in range(n) or c not in range(m) or (r, c) in visited:
  13.                 return
  14.  
  15.             visited.add((r, c))
  16.             directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
  17.  
  18.             for (dr, dc) in directions:
  19.                 row = r + dr
  20.                 col = c + dc
  21.  
  22.                 if row in range(n) and col in range(m) and heights[r][c] <= heights[row][col]:
  23.                     dfs(row, col, visited)
  24.  
  25.         for i in range(n):
  26.             dfs(i, 0, p_visited)
  27.             dfs(i, m-1, a_visited)
  28.  
  29.         for j in range(m):
  30.             dfs(0, j, p_visited)
  31.             dfs(n-1, j, a_visited)
  32.  
  33.         for r in range(n):
  34.             for c in range(m):
  35.                 if (r, c) in p_visited and (r, c) in a_visited:
  36.                     result.append([r, c])
  37.  
  38.         return result
  39.  
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement