Skip to content

Commit 71a8d1b

Browse files
committed
solve 3
1 parent 77badff commit 71a8d1b

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
'''
2+
시간 복잡도: O(m * n)
3+
- 각 바다에서 BFS를 한 번씩 수행하며, 각 셀을 최대 한 번씩 방문하므로 O(m * n)입니다.
4+
5+
공간 복잡도: O(m * n)
6+
- BFS 탐색을 위한 큐와 방문한 셀을 저장하는 집합(set)이 필요하므로 O(m * n)입니다.
7+
'''
8+
9+
from collections import deque
10+
from typing import List
11+
12+
class Solution:
13+
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
14+
m, n = len(heights), len(heights[0])
15+
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
16+
17+
def bfs(starts):
18+
queue = deque(starts)
19+
reachable = set(starts)
20+
21+
while queue:
22+
r, c = queue.popleft()
23+
for dr, dc in directions:
24+
nr, nc = r + dr, c + dc
25+
if (0 <= nr < m and 0 <= nc < n and
26+
(nr, nc) not in reachable and
27+
heights[nr][nc] >= heights[r][c]): # 물이 흐를 수 있는지 확인
28+
queue.append((nr, nc))
29+
reachable.add((nr, nc))
30+
31+
return reachable
32+
33+
# 태평양(왼쪽과 위쪽 가장자리)에서 시작하는 셀들
34+
pacific_starts = [(0, c) for c in range(n)] + [(r, 0) for r in range(m)]
35+
# 대서양(오른쪽과 아래쪽 가장자리)에서 시작하는 셀들
36+
atlantic_starts = [(m-1, c) for c in range(n)] + [(r, n-1) for r in range(m)]
37+
38+
pacific_reach = bfs(pacific_starts)
39+
atlantic_reach = bfs(atlantic_starts)
40+
41+
return list(pacific_reach & atlantic_reach)
42+
43+
44+
class Solution:
45+
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
46+
if not heights or not heights[0]:
47+
return []
48+
49+
m, n = len(heights), len(heights[0])
50+
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
51+
52+
def dfs(r, c, reachable):
53+
reachable.add((r, c))
54+
for dr, dc in directions:
55+
nr, nc = r + dr, c + dc
56+
if (0 <= nr < m and 0 <= nc < n and
57+
(nr, nc) not in reachable and
58+
heights[nr][nc] >= heights[r][c]):
59+
dfs(nr, nc, reachable)
60+
61+
pacific_reach, atlantic_reach = set(), set()
62+
63+
for c in range(n):
64+
dfs(0, c, pacific_reach)
65+
dfs(m-1, c, atlantic_reach)
66+
67+
for r in range(m):
68+
dfs(r, 0, pacific_reach)
69+
dfs(r, n-1, atlantic_reach)
70+
71+
return list(pacific_reach & atlantic_reach)

0 commit comments

Comments
 (0)