Skip to content

Commit b0b8657

Browse files
committed
pacific-atlantic-water-flow solution
1 parent b4fabee commit b0b8657

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution:
2+
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
3+
# *๋ฌธ์ œ ์ดํ•ด์— ์‹œ๊ฐ„์ด ๋งŽ์ด ๊ฑธ๋ฆผ.
4+
# ๊ฐ ์นธ์—์„œ ์‹œ์ž‘ํ•œ ๋ฌผ์ด ํƒœํ‰์–‘๊ณผ ๋Œ€์„œ์–‘ ๋‘ ๋ฐ”๋‹ค ๋ชจ๋‘๋กœ ํ˜๋Ÿฌ๊ฐˆ ์ˆ˜ ์žˆ๋Š” ์นธ๋“ค ์ฐพ๋Š” ๋ฌธ์ œ(๋†’์ด๊ฐ€ ๊ฐ™๊ฑฐ๋‚˜ ๋‚ฎ์€์ชฝ์œผ๋กœ๋งŒ ๋ฌผ์ด ์ด๋™ ๊ฐ€๋Šฅํ•จ)
5+
# ๋ฌธ์ œ๋ฅผ ์—ญ์œผ๋กœ ์ƒ๊ฐํ•ด์„œ ๋ฐ”๋‹ค์—์„œ ๋ฌผ์ด ์˜ฌ๋ผ๊ฐˆ ์ˆ˜ ์žˆ๋Š” ์นธ(๋” ๋†’๊ฑฐ๋‚˜ ๊ฐ™์€ ์นธ) ์ฐพ๊ธฐ.
6+
# DFS(์‹œ๊ฐ„๋ณต์žก๋„ O(m*n), ๊ณต๊ฐ„๋ณต์žก๋„ O(m*n))
7+
8+
m, n = len(heights), len(heights[0])
9+
pac = set() # ํƒœํ‰์–‘ ๊ฐˆ ์ˆ˜ ์žˆ๋Š” ์นธ ์ €์žฅ
10+
atl = set() # ๋Œ€์„œ์–‘ ๊ฐˆ ์ˆ˜ ์žˆ๋Š” ์นธ ์ €์žฅ
11+
directions = [(-1,0), (1,0), (0,-1), (0,1)] # ์ƒํ•˜์ขŒ์šฐ
12+
13+
def dfs(x, y, visited):
14+
visited.add((x,y)) # ํ˜„์žฌ์œ„์น˜ ๋ฐฉ๋ฌธ์ฒ˜๋ฆฌ
15+
16+
# ํ˜„์žฌ ์œ„์น˜์—์„œ ์ƒํ•˜์ขŒ์šฐ ํƒ์ƒ‰
17+
for dx, dy in directions:
18+
nx, ny = x + dx, y + dy
19+
# ๋‹ค์Œ ์œ„์น˜๊ฐ€ ๋ฒ”์œ„์•ˆ์ด๊ณ , ์•„์ง ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์•˜๊ณ , ๋ฌผ์ด ํ˜๋Ÿฌ๊ฐˆ ์ˆ˜ ์žˆ๋Š” ๋†’์ด๋ผ๋ฉด, ํƒ์ƒ‰
20+
if 0 <= nx < m and 0 <= ny < n and (nx, ny) not in visited and heights[nx][ny] >= heights[x][y]:
21+
dfs(nx, ny, visited)
22+
23+
24+
for i in range(m):
25+
dfs(i, 0, pac) # ์™ผ์ชฝ(pacific)
26+
dfs(i, n-1, atl) # ์˜ค๋ฅธ์ชฝ(atlantic)
27+
for j in range(n):
28+
dfs(0, j, pac) # ์œ„์ชฝ(pacific)
29+
dfs(m-1, j, atl) # ์•„๋ž˜์ชฝ(atlantic)
30+
31+
# ๊ต์ง‘ํ•ฉ(ํƒœํ‰์–‘,๋Œ€์„œ์–‘ ๋ชจ๋‘ ๊ฐˆ ์ˆ˜ ์žˆ๋Š” ์ขŒํ‘œ์˜ ๊ต์ง‘ํ•ฉ)
32+
return list(pac & atl)

0 commit comments

Comments
ย (0)