|
6 | 6 | - 0 <= heights[r][c] <= 10^5
|
7 | 7 |
|
8 | 8 | Time Complexity: O(m*n)
|
9 |
| -- ๊ฐ ์
์ ์ต๋ ํ ๋ฒ์ฉ๋ง ๋ฐฉ๋ฌธํจ |
| 9 | +- ๊ฐ ์
์ ์ต๋ ํ ๋ฒ๋ง ๋ฐฉ๋ฌธํจ |
10 | 10 |
|
11 | 11 | 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๊น์ง ๊ฐ๋ฅ |
14 | 14 |
|
15 | 15 | ํ์ด๋ฐฉ๋ฒ:
|
16 |
| -1. Pacific(์ข์ธก์๋จ)๊ณผ Atlantic(์ฐ์ธกํ๋จ)์ ๊ฒฝ๊ณ์์ ์์ํจ |
17 |
| -2. DFS๋ก ํ์ฌ ๋์ด๋ณด๋ค ๋๊ฑฐ๋ ๊ฐ์ ์ธ์ ์
๋ก๋ง ์ด๋ํจ (๋ฌผ์ ์ -> ์๋๋ก ํ๋ฅด์ง๋ง, ๊ฑฐ๊พธ๋ก ์ ๊ทผํ์ผ๋๊น) |
| 16 | +1. Pacific(์ข์ธก์๋จ)๊ณผ Atlantic(์ฐ์ธกํ๋จ)์ ๊ฒฝ๊ณ์์ ์์ |
| 17 | +2. DFS๋ก ํ์ฌ ๋์ด๋ณด๋ค ๋๊ฑฐ๋ ๊ฐ์ ์ธ์ ์
๋ก๋ง ์ด๋ (์ญ๋ฐฉํฅ ์ ๊ทผ) |
18 | 18 | 3. ๊ฐ ๋ฐ๋ค์์ ๋๋ฌ ๊ฐ๋ฅํ ์
๋ค์ Set์ ์ ์ฅ
|
19 |
| -4. ๋ Set์ ๊ต์งํฉ์ด ์ ๋ต (์์ชฝ ๋ฐ๋ค๋ก ๋ชจ๋ ํ๋ฅผ ์ ์๋ ์ง์ ๋ค) |
| 19 | +4. ๋ Set์ ๊ต์งํฉ์ผ๋ก ์์ชฝ ๋ฐ๋ค ๋ชจ๋ ๋๋ฌ ๊ฐ๋ฅํ ์ง์ ๋ฐํ |
20 | 20 | """
|
| 21 | +# ์๋ณธ ์ฝ๋ |
21 | 22 | class Solution:
|
22 | 23 | def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
|
23 | 24 | if not heights:
|
@@ -51,3 +52,43 @@ def dfs(r, c, visited):
|
51 | 52 | dfs(r, cols-1, atlantic)
|
52 | 53 |
|
53 | 54 | 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