Skip to content

Commit c1afebb

Browse files
committed
leetcode.com 417. Pacific Atlantic Water Flow
문제 링크: https://leetcode.com/problems/pacific-atlantic-water-flow/description/
1 parent 337bb79 commit c1afebb

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
6+
MAX_ROW = len(heights)
7+
MAX_COL = len(heights[0])
8+
pacific: List[List] = [[False for _ in range(MAX_COL)] for _ in range(MAX_ROW)]
9+
atlantic: List[List] = [[False for _ in range(MAX_COL)] for _ in range(MAX_ROW)]
10+
11+
def dfs(visited: List[List], prev_height, r, c):
12+
if 0 <= r < MAX_ROW \
13+
and 0 <= c < MAX_COL \
14+
and visited[r][c] == False \
15+
and prev_height <= heights[r][c]:
16+
visited[r][c] = True
17+
18+
dfs(visited, heights[r][c], r - 1, c)
19+
dfs(visited, heights[r][c], r, c + 1)
20+
dfs(visited, heights[r][c], r + 1, c)
21+
dfs(visited, heights[r][c], r, c - 1)
22+
23+
for r in range(0, MAX_ROW):
24+
dfs(pacific, 0, r, 0)
25+
dfs(atlantic, 0, r, MAX_COL - 1)
26+
27+
for c in range(0, MAX_COL):
28+
dfs(pacific, 0, 0, c)
29+
dfs(atlantic, 0, MAX_ROW - 1, c)
30+
31+
answer: List[List] = []
32+
33+
for r in range(0, MAX_ROW):
34+
for c in range(0, MAX_COL):
35+
if pacific[r][c] and atlantic[r][c]:
36+
answer.append([r, c])
37+
38+
return answer
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
from unittest import TestCase
2+
from main import Solution
3+
4+
class TestSolution(TestCase):
5+
def test1_pacific_atlantic(self):
6+
sol = Solution()
7+
self.assertEqual([[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]],\
8+
sol.pacificAtlantic([[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]))
9+
10+
def test2_pacific_atlantic(self):
11+
sol = Solution()
12+
self.assertEqual([[0,0]], sol.pacificAtlantic([[1]]))

0 commit comments

Comments
 (0)