Skip to content

Commit 9374bd8

Browse files
committed
DaleStudy#260 pacific-atlantic-water-flow
1 parent 932fa8e commit 9374bd8

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
"""
2+
ํ’€์ด :
3+
๋น—๋ฌผ์ด ํ˜๋Ÿฌ๊ฐ€์„œ ๋ฐ”๋‹ค์— ๋„์ฐฉํ•˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ์•„๋‹Œ ์—ญ์œผ๋กœ ๋ฐ”๋‹ค์—์„œ ์ถœ๋ฐœํ•ด์„œ ๋„๋‹ฌํ•  ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ๋ฅผ ์ฐพ๋Š”๋‹ค
4+
4๋ฐฉํ–ฅ ์ค‘์— height๊ฐ€ ํ˜„์žฌ ์œ„์น˜๋ณด๋‹ค ๋†’๊ฑฐ๋‚˜ ๊ฐ™์œผ๋ฉด ์œ„๋กœ ํ˜๋Ÿฌ๊ฐˆ ์ˆ˜ ์žˆ๊ณ  visited set์— ์ €์žฅํ•ด์„œ
5+
์ด๋ฏธ ๋„๋‹ฌํ•œ ๊ณณ์€ return ์œผ๋กœ ์ฒ˜๋ฆฌํ•œ๋‹ค
6+
๋ฐ”๋‹ค์™€ ์œ„์•„๋ž˜๋กœ ๋งž๋‹ฟ์€ ํ•ด์•ˆ๊ณผ ์ขŒ์šฐ๋กœ ๋งž๋‹ฟ์€ ํ•ด์•ˆ์—์„œ ๊ฐ๊ฐ ์ถœ๋ฐœํ•˜๋„๋ก ๋‘๋ฒˆ์˜ ๋ฐ˜๋ณต๋ฌธ์„ ์ˆ˜ํ–‰
7+
8+
r, c : ํ–‰๋ ฌ์˜ ๊ธธ์ด
9+
10+
TC : O(R * C)
11+
visited_set์„ ํ†ตํ•ด pacific, atlantic์ด ์ตœ์•…์˜ ๊ฒฝ์šฐ์—๋„ ์„ฌ ์ „์ฒด๋ฅผ ํ•œ๋ฒˆ์”ฉ ์ˆœํšŒํ•˜๋ฏ€๋กœ
12+
13+
SC : O(R * C)
14+
๊ฐ set์˜ ํฌ๊ธฐ์™€ dfs ํ˜ธ์ถœ ์Šคํƒ์€ ์„ฌ ํฌ๊ธฐ์— ๋น„๋ก€ํ•˜๋ฏ€๋กœ
15+
"""
16+
17+
class Solution:
18+
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
19+
paci_visited, atl_visited = set(), set()
20+
n_rows = len(heights)
21+
n_cols = len(heights[0])
22+
23+
def dfs(r: int, c: int, visited: set) -> None:
24+
if (r, c) in visited:
25+
return
26+
visited.add((r, c))
27+
for (m, n) in [(r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)]:
28+
if 0 <= m < n_rows and 0 <= n < n_cols:
29+
if heights[r][c] <= heights[m][n]:
30+
dfs(m, n, visited)
31+
32+
for r in range(n_rows):
33+
dfs(r, 0, paci_visited)
34+
dfs(r, n_cols - 1, atl_visited)
35+
36+
for c in range(n_cols):
37+
dfs(0, c, paci_visited)
38+
dfs(n_rows - 1, c, atl_visited)
39+
40+
result = []
41+
for both in paci_visited.intersection(atl_visited):
42+
result.append(list(both))
43+
44+
return result

0 commit comments

Comments
ย (0)