Skip to content

Commit 0cfc687

Browse files
committed
feat: 417. Pacific Atlantic Water Flow
1 parent 2bd54e9 commit 0cfc687

File tree

1 file changed

+131
-0
lines changed

1 file changed

+131
-0
lines changed
Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
// n: height, m: width
2+
// Time complexity: O(n*m)
3+
// Space complexity: O(n*m)
4+
5+
class _Queue {
6+
constructor() {
7+
this.q = [];
8+
this.start = 0;
9+
this.end = 0;
10+
}
11+
12+
isEmpty() {
13+
return this.start === this.end;
14+
}
15+
16+
push(value) {
17+
this.q.push(value);
18+
this.end++;
19+
}
20+
21+
pop() {
22+
const rv = this.q[this.start];
23+
delete this.q[this.start++];
24+
return rv;
25+
}
26+
}
27+
/**
28+
* @param {number[][]} heights
29+
* @return {number[][]}
30+
*/
31+
var pacificAtlantic = function (heights) {
32+
const dy = [1, 0, -1, 0];
33+
const dx = [0, 1, 0, -1];
34+
35+
const h = heights.length;
36+
const w = heights[0].length;
37+
const checked = Array.from({ length: h }, () =>
38+
Array.from({ length: w }, () => [false, false])
39+
);
40+
41+
// 태평양
42+
const pacific = new _Queue();
43+
44+
for (let i = 0; i < h; i++) {
45+
if (!checked[i][0][0]) {
46+
pacific.push([i, 0]);
47+
checked[i][0][0] = true;
48+
}
49+
}
50+
51+
for (let i = 0; i < w; i++) {
52+
if (!checked[0][i][0]) {
53+
pacific.push([0, i]);
54+
checked[0][i][0] = true;
55+
}
56+
}
57+
58+
while (!pacific.isEmpty()) {
59+
const [cy, cx] = pacific.pop();
60+
61+
for (let i = 0; i < dy.length; i++) {
62+
const ny = cy + dy[i];
63+
const nx = cx + dx[i];
64+
65+
if (
66+
ny >= 0 &&
67+
ny < h &&
68+
nx >= 0 &&
69+
nx < w &&
70+
!checked[ny][nx][0] &&
71+
heights[ny][nx] >= heights[cy][cx]
72+
) {
73+
checked[ny][nx][0] = true;
74+
pacific.push([ny, nx]);
75+
}
76+
}
77+
}
78+
79+
// 대서양
80+
const answer = [];
81+
const atlantic = new _Queue();
82+
83+
for (let i = 0; i < h; i++) {
84+
if (!checked[i][w - 1][1]) {
85+
atlantic.push([i, w - 1]);
86+
checked[i][w - 1][1] = true;
87+
}
88+
89+
if (checked[i][w - 1][0] === true) {
90+
answer.push([i, w - 1]);
91+
}
92+
}
93+
94+
for (let i = 0; i < w; i++) {
95+
if (!checked[h - 1][i][1]) {
96+
atlantic.push([h - 1, i]);
97+
checked[h - 1][i][1] = true;
98+
99+
if (checked[h - 1][i][0] === true) {
100+
answer.push([h - 1, i]);
101+
}
102+
}
103+
}
104+
105+
while (!atlantic.isEmpty()) {
106+
const [cy, cx] = atlantic.pop();
107+
108+
for (let i = 0; i < dy.length; i++) {
109+
const ny = cy + dy[i];
110+
const nx = cx + dx[i];
111+
112+
if (
113+
ny >= 0 &&
114+
ny < h &&
115+
nx >= 0 &&
116+
nx < w &&
117+
!checked[ny][nx][1] &&
118+
heights[ny][nx] >= heights[cy][cx]
119+
) {
120+
if (checked[ny][nx][0] === true) {
121+
answer.push([ny, nx]);
122+
}
123+
124+
checked[ny][nx][1] = true;
125+
atlantic.push([ny, nx]);
126+
}
127+
}
128+
}
129+
130+
return answer;
131+
};

0 commit comments

Comments
 (0)