-
-
Notifications
You must be signed in to change notification settings - Fork 9k
/
Copy pathSolution.py
32 lines (31 loc) · 1.15 KB
/
Solution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
def bfs(q, vis):
while q:
for _ in range(len(q), 0, -1):
i, j = q.popleft()
for a, b in [[0, -1], [0, 1], [1, 0], [-1, 0]]:
x, y = i + a, j + b
if 0 <= x < m and 0 <= y < n and (x, y) not in vis and heights[x][y] >= heights[i][j]:
vis.add((x, y))
q.append((x, y))
m, n = len(heights), len(heights[0])
vis1, vis2 = set(), set()
q1 = deque()
q2 = deque()
for i in range(m):
for j in range(n):
if i == 0 or j == 0:
vis1.add((i, j))
q1.append((i, j))
if i == m - 1 or j == n - 1:
vis2.add((i, j))
q2.append((i, j))
bfs(q1, vis1)
bfs(q2, vis2)
ans = []
for i in range(m):
for j in range(n):
if (i, j) in vis1 and (i, j) in vis2:
ans.append((i, j))
return ans