|
| 1 | +""" |
| 2 | +Constraints: |
| 3 | +- m == heights.length |
| 4 | +- n == heights[r].length |
| 5 | +- 1 <= m, n <= 200 |
| 6 | +- 0 <= heights[r][c] <= 10^5 |
| 7 | +
|
| 8 | +Time Complexity: O(m*n) |
| 9 | +- 각 셀을 최대 한 번씩만 방문함 |
| 10 | +
|
| 11 | +Space Complexity: O(m*n) |
| 12 | +- visited sets(pacific, atlantic)가 최대 m*n 크기 |
| 13 | +- 재귀 호출 스택도 최대 m*n 깊이 가능 |
| 14 | +
|
| 15 | +풀이방법: |
| 16 | +1. Pacific(좌측상단)과 Atlantic(우측하단)의 경계에서 시작함 |
| 17 | +2. DFS로 현재 높이보다 높거나 같은 인접 셀로만 이동함 (물은 위 -> 아래로 흐르지만, 거꾸로 접근했으니까) |
| 18 | +3. 각 바다에서 도달 가능한 셀들을 Set에 저장 |
| 19 | +4. 두 Set의 교집합이 정답 (양쪽 바다로 모두 흐를 수 있는 지점들) |
| 20 | +""" |
| 21 | +class Solution: |
| 22 | + def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]: |
| 23 | + if not heights: |
| 24 | + return [] |
| 25 | + |
| 26 | + rows, cols = len(heights), len(heights[0]) |
| 27 | + pacific = set() |
| 28 | + atlantic = set() |
| 29 | + |
| 30 | + def dfs(r, c, visited): |
| 31 | + visited.add((r, c)) |
| 32 | + directions = [(1,0), (-1,0), (0,1), (0,-1)] |
| 33 | + |
| 34 | + for dr, dc in directions: |
| 35 | + new_r, new_c = r + dr, c + dc |
| 36 | + if (new_r < 0 or new_r >= rows or |
| 37 | + new_c < 0 or new_c >= cols or |
| 38 | + (new_r, new_c) in visited): |
| 39 | + continue |
| 40 | + if heights[new_r][new_c] >= heights[r][c]: |
| 41 | + dfs(new_r, new_c, visited) |
| 42 | + |
| 43 | + for c in range(cols): |
| 44 | + dfs(0, c, pacific) |
| 45 | + for r in range(rows): |
| 46 | + dfs(r, 0, pacific) |
| 47 | + |
| 48 | + for c in range(cols): |
| 49 | + dfs(rows-1, c, atlantic) |
| 50 | + for r in range(rows): |
| 51 | + dfs(r, cols-1, atlantic) |
| 52 | + |
| 53 | + return list(pacific & atlantic) |
0 commit comments