|
| 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