Advertisement
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]]:
- n, m = len(heights), len(heights[0])
- result = []
- p_visited = set()
- a_visited = set()
- def bfs(r, c, visited):
- if r not in range(n) or c not in range(m) or (r, c) in visited:
- return
- from collections import deque
- q = deque()
- visited.add((r, c))
- q.append((r, c))
- while(q):
- (row, col) = q.popleft()
- directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
- for dr, dc in directions:
- r = row + dr
- c = col + dc
- if r in range(n) and c in range(m) and heights[r][c] >= heights[row][col] and (r, c) not in visited:
- visited.add((r, c))
- q.append((r, c))
- for i in range(n):
- bfs(i, 0, p_visited)
- bfs(i, m-1, a_visited)
- for j in range(m):
- bfs(0, j, p_visited)
- bfs(n-1, j, a_visited)
- for r in range(n):
- for c in range(m):
- if (r, c) in p_visited and (r, c) in a_visited:
- result.append([r, c])
- return result
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement