Skip to content

Commit 50d78a0

Browse files
committed
Solution: Pacific Atlantic Water Flow
1 parent 61b1e5d commit 50d78a0

File tree

1 file changed

+101
-0
lines changed

1 file changed

+101
-0
lines changed
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
/*
2+
풀이
3+
- BFS를 이용하여 풀이할 수 있습니다
4+
- 주어진 배열의 가장자리에서부터 시작하는 BFS를 pacific과 atlantic에 대해 각각 실행합니다
5+
6+
Big O
7+
- M: 주어진 배열의 행의 개수
8+
- N: 주어진 배열의 열의 개수
9+
- Time complexity: O(MN)
10+
- 탐색을 진행하는 회수는 배열의 원소 개수에 비례하여 증가합니다
11+
- Space complexity: O(MN)
12+
- queue의 최대 크기는 배열의 원소 개수에 비례하여 증가합니다
13+
- memo 배열의 크기는 배열의 원소 개수에 비례하여 증가합니다
14+
*/
15+
16+
type pair struct {
17+
pacific bool
18+
atlantic bool
19+
}
20+
21+
func pacificAtlantic(heights [][]int) [][]int {
22+
var res [][]int
23+
24+
m, n := len(heights), len(heights[0])
25+
26+
dr := []int{0, 0, 1, -1}
27+
dc := []int{1, -1, 0, 0}
28+
29+
// 모든 r, c에 대해 memo[r][c] = {pacific: false, atlantic: false}로 초기화합니다
30+
memo := make([][]pair, m)
31+
for r := range memo {
32+
memo[r] = make([]pair, n)
33+
}
34+
35+
queue := make([][]int, 0)
36+
37+
// pacific에서 시작하는 BFS
38+
for c := 0; c < n; c++ {
39+
queue = append(queue, []int{0, c})
40+
}
41+
for r := 1; r < m; r++ {
42+
queue = append(queue, []int{r, 0})
43+
}
44+
45+
for len(queue) > 0 {
46+
r, c := queue[0][0], queue[0][1]
47+
queue = queue[1:]
48+
49+
memo[r][c].pacific = true
50+
51+
for i := 0; i < 4; i++ {
52+
nr, nc := r+dr[i], c+dc[i]
53+
54+
if !(0 <= nr && nr < m && 0 <= nc && nc < n) {
55+
continue
56+
}
57+
58+
if heights[r][c] <= heights[nr][nc] && !memo[nr][nc].pacific {
59+
queue = append(queue, []int{nr, nc})
60+
}
61+
}
62+
}
63+
64+
// atlantic에서 시작하는 BFS
65+
for c := 0; c < n; c++ {
66+
queue = append(queue, []int{m - 1, c})
67+
}
68+
for r := 0; r < m-1; r++ {
69+
queue = append(queue, []int{r, n - 1})
70+
}
71+
72+
for len(queue) > 0 {
73+
r, c := queue[0][0], queue[0][1]
74+
queue = queue[1:]
75+
76+
memo[r][c].atlantic = true
77+
78+
for i := 0; i < 4; i++ {
79+
nr, nc := r+dr[i], c+dc[i]
80+
81+
if !(0 <= nr && nr < m && 0 <= nc && nc < n) {
82+
continue
83+
}
84+
85+
if heights[r][c] <= heights[nr][nc] && !memo[nr][nc].atlantic {
86+
memo[nr][nc].atlantic = true
87+
queue = append(queue, []int{nr, nc})
88+
}
89+
}
90+
}
91+
92+
for r, row := range memo {
93+
for c, el := range row {
94+
if el.pacific && el.atlantic {
95+
res = append(res, []int{r, c})
96+
}
97+
}
98+
}
99+
100+
return res
101+
}

0 commit comments

Comments
 (0)