Skip to content

Commit e56a068

Browse files
committed
Sync LeetCode submission - Pacific Atlantic Water Flow (python3)
1 parent 1bf60ce commit e56a068

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution:
2+
3+
4+
def pacificAtlantic(self, matrix: List[List[int]]) -> List[List[int]]:
5+
if not matrix:
6+
return []
7+
8+
self.rows, self.cols = len(matrix), len(matrix[0])
9+
p_visited = set()
10+
a_visited = set()
11+
self.directions = ((0, 1), (0, -1), (1, 0), (-1, 0))
12+
13+
for row in range(self.rows):
14+
self.traverse(row, 0, matrix,p_visited)
15+
self.traverse(row, self.cols - 1, matrix,a_visited)
16+
17+
for col in range(self.cols):
18+
self.traverse(0, col, matrix,p_visited)
19+
self.traverse(self.rows - 1, col, matrix,a_visited)
20+
21+
return list(p_visited & a_visited)
22+
23+
24+
def traverse(self,i, j, matrix,visited):
25+
if (i, j) in visited:
26+
return
27+
visited.add((i, j))
28+
# Traverse neighbors.
29+
for direction in self.directions:
30+
next_i, next_j = i + direction[0], j + direction[1]
31+
if 0 <= next_i < self.rows and 0 <= next_j < self.cols:
32+
if matrix[next_i][next_j] >= matrix[i][j]:
33+
self.traverse(next_i, next_j, matrix,visited)
34+
35+

0 commit comments

Comments
 (0)