Advertisement
smj007

Untitled

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