Skip to content

Commit 1657c59

Browse files
committed
solve: pacific atlantic water flow
1 parent 73ea4ab commit 1657c59

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
/**
2+
* pacific(0행, 0열), atlantic(row-1행, column-1열)에서 높이가 같거나 높은 곳으로 순회한다.
3+
* 그리고 pacific에서 온 물과 atlantic에서 온 물이 만나는 곳을 정답으로 만든다.
4+
*
5+
* TC: O(row * column)
6+
* queue에 최대 row * column만큼 들어갑니다.
7+
*
8+
* SC: O(row * column)
9+
* pacific 또는 atlantic에 최대 row * column만큼 들어갑니다.
10+
*/
11+
12+
/**
13+
* @param {number[][]} heights
14+
* @return {number[][]}
15+
*/
16+
var pacificAtlantic = function (heights) {
17+
const ROW = heights.length;
18+
const COLUMN = heights[0].length;
19+
const DIRECTION = [
20+
[-1, 0],
21+
[1, 0],
22+
[0, -1],
23+
[0, 1],
24+
];
25+
const result = [];
26+
const queue = [];
27+
28+
for (let c = 0; c < COLUMN; c++) {
29+
queue.push([0, c]);
30+
}
31+
for (let r = 1; r < ROW; r++) {
32+
queue.push([r, 0]);
33+
}
34+
35+
const pacific = new Set();
36+
while (queue.length > 0) {
37+
const [row, column] = queue.shift();
38+
pacific.add(generateKey(row, column));
39+
for (const [directionR, directionC] of DIRECTION) {
40+
const [nextRow, nextColumn] = [row + directionR, column + directionC];
41+
if (
42+
isValidPosition(nextRow, nextColumn) &&
43+
heights[row][column] <= heights[nextRow][nextColumn] &&
44+
!pacific.has(generateKey(nextRow, nextColumn))
45+
) {
46+
queue.push([nextRow, nextColumn]);
47+
}
48+
}
49+
}
50+
51+
for (let c = 0; c < COLUMN; c++) {
52+
queue.push([ROW - 1, c]);
53+
}
54+
for (let r = 0; r < ROW - 1; r++) {
55+
queue.push([r, COLUMN - 1]);
56+
}
57+
58+
const atlantic = new Set();
59+
while (queue.length > 0) {
60+
const [row, column] = queue.shift();
61+
const key = generateKey(row, column);
62+
atlantic.add(key);
63+
if (pacific.has(key)) {
64+
pacific.delete(key);
65+
result.push([row, column]);
66+
}
67+
for (const [directionR, directionC] of DIRECTION) {
68+
const [nextRow, nextColumn] = [row + directionR, column + directionC];
69+
if (
70+
isValidPosition(nextRow, nextColumn) &&
71+
heights[row][column] <= heights[nextRow][nextColumn] &&
72+
!atlantic.has(generateKey(nextRow, nextColumn))
73+
) {
74+
queue.push([nextRow, nextColumn]);
75+
}
76+
}
77+
}
78+
79+
return result;
80+
81+
function isValidPosition(row, column) {
82+
if (row < 0 || ROW <= row) {
83+
return false;
84+
}
85+
if (column < 0 || COLUMN <= column) {
86+
return false;
87+
}
88+
return true;
89+
}
90+
91+
function generateKey(row, column) {
92+
return `${row},${column}`;
93+
}
94+
};

0 commit comments

Comments
 (0)