-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy path0417-pacific-atlantic-water-flow.py
49 lines (40 loc) · 1.52 KB
/
0417-pacific-atlantic-water-flow.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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# time complexity: O(m*n)
# space complexity: O(m*n)
from collections import deque
from typing import List
class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
ROW = len(heights)
COL = len(heights[0])
if not ROW or not COL:
return []
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
pacificQueue = deque()
atlanticQueue = deque()
for i in range(ROW):
pacificQueue.append((i, 0))
atlanticQueue.append((i, COL - 1))
for i in range(COL):
pacificQueue.append((0, i))
atlanticQueue.append((ROW - 1, i))
def bfs(queue):
reachable = set()
while queue:
currX, currY = queue.popleft()
reachable.add((currX, currY))
for (dX, dY) in directions:
nextX = currX + dX
nextY = currY + dY
if nextX < 0 or nextX >= ROW or nextY < 0 or nextY >= COL:
continue
if (nextX, nextY) in reachable:
continue
if heights[currX][currY] > heights[nextX][nextY]:
continue
queue.append((nextX, nextY))
return reachable
pacificSet = bfs(pacificQueue)
atlanticSet = bfs(atlanticQueue)
return list(pacificSet.intersection(atlanticSet))
heights = [[1, 1], [1, 1], [1, 1]]
print(Solution().pacificAtlantic(heights))