Skip to content

Commit 76c9478

Browse files
committed
pacific-atlantic-water-flow solution
1 parent a33a903 commit 76c9478

1 file changed

Lines changed: 89 additions & 0 deletions

File tree

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
/**
2+
* @param heights - μ…€μ˜ ν•΄λ°œκ³ λ„ λ°°μ—΄
3+
* @returns
4+
* @description
5+
* - μΈμ ‘ν•œ μ…€μ˜ 높이가 μž‘κ±°λ‚˜ κ°™μœΌλ©΄ 빗물이 흐λ₯Ό 수 있음
6+
* - 바닀에 μΈμ ‘ν•œ μ…€μ—μ„œλŠ” λ°”λ‹€λ‘œ 물이 흐λ₯Ό 수 있음
7+
* - νƒœν‰μ–‘κ³Ό λŒ€μ„œμ–‘ λͺ¨λ‘λ‘œ 흐λ₯Ό 수 μžˆλŠ” 경둜 λ°˜ν™˜
8+
* - κ²°κ΅­ [0, n] κ³Ό [m, 0]λŠ” λ°˜λ“œμ‹œ 포함
9+
*
10+
* 1. μ—­μˆœμœΌλ‘œ κ°€λŠ”κ²Œ μœ λ¦¬ν•˜λ‹€λŠ” 힌트λ₯Ό 채택
11+
* 2. λͺ¨λ“  μ…€μ˜ 이동 κ°€λŠ₯ λ°©ν–₯을 νŒŒμ•… (dfs, bfs)
12+
*/
13+
14+
function pacificAtlantic(heights: number[][]): number[][] {
15+
const yMax = heights.length;
16+
const xMax = heights[0].length;
17+
18+
// νƒœν‰μ–‘, λŒ€μ„œμ–‘μ˜ visit 체크λ₯Ό μœ„ν•œ set
19+
const pacific = new Set<string>();
20+
const atlantic = new Set<string>();
21+
22+
const result: number[][] = [];
23+
function dfs(y: number, x: number, visited: Set<string>, prevHeight: number) {
24+
const key = `${y},${x}`;
25+
26+
if (
27+
x < 0 ||
28+
x >= xMax ||
29+
y < 0 ||
30+
y >= yMax ||
31+
visited.has(key) ||
32+
prevHeight > heights[y][x]
33+
) {
34+
return;
35+
}
36+
37+
visited.add(key);
38+
dfs(y, x + 1, visited, heights[y][x]);
39+
dfs(y, x - 1, visited, heights[y][x]);
40+
dfs(y + 1, x, visited, heights[y][x]);
41+
dfs(y - 1, x, visited, heights[y][x]);
42+
}
43+
44+
// 맨 μ–‘ 끝μͺ½μ„ dfs의 μ‹œμž‘μ μœΌλ‘œ μ§€μ •
45+
for (let i = 0; i < yMax; i++) {
46+
dfs(i, 0, pacific, heights[i][0]);
47+
dfs(i, xMax - 1, atlantic, heights[i][xMax - 1]);
48+
}
49+
50+
for (let j = 0; j < xMax; j++) {
51+
dfs(0, j, pacific, heights[0][j]);
52+
dfs(yMax - 1, j, atlantic, heights[yMax - 1][j]);
53+
}
54+
55+
// μœ λ‹ˆμ˜¨ κ°’ 체크
56+
for (let i = 0; i < yMax; i++) {
57+
for (let j = 0; j < xMax; j++) {
58+
const key = `${i},${j}`;
59+
60+
if (pacific.has(key) && atlantic.has(key)) {
61+
result.push([i, j]);
62+
}
63+
}
64+
}
65+
66+
return result;
67+
}
68+
69+
const heights = [
70+
[1, 2, 2, 3, 5],
71+
[3, 2, 3, 4, 4],
72+
[2, 4, 5, 3, 1],
73+
[6, 7, 1, 4, 5],
74+
[5, 1, 1, 2, 4],
75+
];
76+
77+
pacificAtlantic(heights);
78+
79+
// νƒœ 평 μ–‘ (Pacific)
80+
// ~ ~ ~ ~ ~ ~
81+
// ~ [1] [2] [2] [3] (5) ~ <-- 였λ₯Έμͺ½/μ•„λž˜λŠ” λŒ€μ„œμ–‘
82+
// ~ [3] [2] [3] (4) (4) ~
83+
// ~ [2] [4] (5) [3] [1] ~
84+
// ~ (6) (7) (1) [4] [5] ~
85+
// ~ (5) [1] [1] [2] [4] ~
86+
// ~ ~ ~ ~ ~ ~
87+
// λŒ€ μ„œ μ–‘ (Atlantic)
88+
89+

0 commit comments

Comments
Β (0)