Skip to content

Commit 06282b9

Browse files
committed
Solved Pacific Atlantic Water Flow problem with code review
1 parent 9b492e4 commit 06282b9

File tree

1 file changed

+47
-6
lines changed

1 file changed

+47
-6
lines changed

โ€Žpacific-atlantic-water-flow/KwonNayeon.py

Lines changed: 47 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,19 @@
66
- 0 <= heights[r][c] <= 10^5
77
88
Time Complexity: O(m*n)
9-
- ๊ฐ ์…€์„ ์ตœ๋Œ€ ํ•œ ๋ฒˆ์”ฉ๋งŒ ๋ฐฉ๋ฌธํ•จ
9+
- ๊ฐ ์…€์„ ์ตœ๋Œ€ ํ•œ ๋ฒˆ๋งŒ ๋ฐฉ๋ฌธํ•จ
1010
1111
Space Complexity: O(m*n)
12-
- visited sets(pacific, atlantic)๊ฐ€ ์ตœ๋Œ€ m*n ํฌ๊ธฐ
13-
- ์žฌ๊ท€ ํ˜ธ์ถœ ์Šคํƒ๋„ ์ตœ๋Œ€ m*n ๊นŠ์ด ๊ฐ€๋Šฅ
12+
- visited sets(pacific, atlantic)์€ ์ตœ๋Œ€ m*n ํฌ๊ธฐ
13+
- ์žฌ๊ท€ ํ˜ธ์ถœ ์Šคํƒ๋„ ์ตœ๋Œ€ m*n๊นŒ์ง€ ๊ฐ€๋Šฅ
1414
1515
ํ’€์ด๋ฐฉ๋ฒ•:
16-
1. Pacific(์ขŒ์ธก์ƒ๋‹จ)๊ณผ Atlantic(์šฐ์ธกํ•˜๋‹จ)์˜ ๊ฒฝ๊ณ„์—์„œ ์‹œ์ž‘ํ•จ
17-
2. DFS๋กœ ํ˜„์žฌ ๋†’์ด๋ณด๋‹ค ๋†’๊ฑฐ๋‚˜ ๊ฐ™์€ ์ธ์ ‘ ์…€๋กœ๋งŒ ์ด๋™ํ•จ (๋ฌผ์€ ์œ„ -> ์•„๋ž˜๋กœ ํ๋ฅด์ง€๋งŒ, ๊ฑฐ๊พธ๋กœ ์ ‘๊ทผํ–ˆ์œผ๋‹ˆ๊นŒ)
16+
1. Pacific(์ขŒ์ธก์ƒ๋‹จ)๊ณผ Atlantic(์šฐ์ธกํ•˜๋‹จ)์˜ ๊ฒฝ๊ณ„์—์„œ ์‹œ์ž‘
17+
2. DFS๋กœ ํ˜„์žฌ ๋†’์ด๋ณด๋‹ค ๋†’๊ฑฐ๋‚˜ ๊ฐ™์€ ์ธ์ ‘ ์…€๋กœ๋งŒ ์ด๋™ (์—ญ๋ฐฉํ–ฅ ์ ‘๊ทผ)
1818
3. ๊ฐ ๋ฐ”๋‹ค์—์„œ ๋„๋‹ฌ ๊ฐ€๋Šฅํ•œ ์…€๋“ค์„ Set์— ์ €์žฅ
19-
4. ๋‘ Set์˜ ๊ต์ง‘ํ•ฉ์ด ์ •๋‹ต (์–‘์ชฝ ๋ฐ”๋‹ค๋กœ ๋ชจ๋‘ ํ๋ฅผ ์ˆ˜ ์žˆ๋Š” ์ง€์ ๋“ค)
19+
4. ๋‘ Set์˜ ๊ต์ง‘ํ•ฉ์œผ๋กœ ์–‘์ชฝ ๋ฐ”๋‹ค ๋ชจ๋‘ ๋„๋‹ฌ ๊ฐ€๋Šฅํ•œ ์ง€์  ๋ฐ˜ํ™˜
2020
"""
21+
# ์›๋ณธ ์ฝ”๋“œ
2122
class Solution:
2223
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
2324
if not heights:
@@ -51,3 +52,43 @@ def dfs(r, c, visited):
5152
dfs(r, cols-1, atlantic)
5253

5354
return list(pacific & atlantic)
55+
56+
# ๊ฐœ์„ ๋œ ์ฝ”๋“œ
57+
class Solution:
58+
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
59+
rows, cols = len(heights), len(heights[0])
60+
61+
# ๊ฐ ๋ฐ”๋‹ค์—์„œ ๋„๋‹ฌ ๊ฐ€๋Šฅํ•œ ์œ„์น˜ ์ €์žฅ
62+
pacific = set()
63+
atlantic = set()
64+
65+
def dfs(r, c, visited):
66+
# ํ˜„์žฌ ์œ„์น˜ ๋ฐฉ๋ฌธ ์ฒ˜๋ฆฌ
67+
visited.add((r, c))
68+
69+
# ๋„ค ๋ฐฉํ–ฅ ํƒ์ƒ‰ (์˜ค๋ฅธ์ชฝ, ์œ„, ์™ผ์ชฝ, ์•„๋ž˜)
70+
for dr, dc in [(0, 1), (-1, 0), (0, -1), (1, 0)]:
71+
new_r, new_c = r + dr, c + dc
72+
73+
# ๊ฒฝ๊ณ„ ์ฒดํฌ, ๋ฐฉ๋ฌธx ์ฒดํฌ, ๋†’์ด ์ฒดํฌ
74+
if (0 <= new_r < rows and
75+
0 <= new_c < cols and
76+
(new_r, new_c) not in visited and
77+
heights[new_r][new_c] >= heights[r][c]):
78+
79+
dfs(new_r, new_c, visited)
80+
81+
# Pacific ๊ฒฝ๊ณ„์—์„œ ์‹œ์ž‘ (์œ„ + ์™ผ์ชฝ)
82+
for c in range(cols):
83+
dfs(0, c, pacific)
84+
for r in range(rows):
85+
dfs(r, 0, pacific)
86+
87+
# Atlantic ๊ฒฝ๊ณ„์—์„œ ์‹œ์ž‘ (์•„๋ž˜ + ์˜ค๋ฅธ์ชฝ)
88+
for c in range(cols):
89+
dfs(rows-1, c, atlantic)
90+
for r in range(rows):
91+
dfs(r, cols-1, atlantic)
92+
93+
# ์–‘์ชฝ ๋ฐ”๋‹ค ๋ชจ๋‘ ๋„๋‹ฌ ๊ฐ€๋Šฅํ•œ ์œ„์น˜ ๋ฐ˜ํ™˜
94+
return [[r, c] for r, c in pacific & atlantic]

0 commit comments

Comments
ย (0)