Skip to content

Commit 61a6b72

Browse files
committed
feat(soobing): week9 > pacific-atlantic-water-flow
1 parent c683a1c commit 61a6b72

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/**
2+
* 문제 설명
3+
* - 비가 내렸을 때, 태평양과 대서양 모두로 물이 흐를 수 있는 지점을 찾아 반환하는 문제입니다.
4+
* 아이디어
5+
* 1) BFS/DFS
6+
* - 각 바다에서 역방향으로 물이 도달할 수 있는 셀을 탐색한 후, 두 바다 모두에 도달 가능한 셀의 교집합 구하기
7+
*
8+
*/
9+
10+
function pacificAtlantic(heights: number[][]): number[][] {
11+
const m = heights.length;
12+
const n = heights[0].length;
13+
14+
const pacific = Array.from({ length: m }, () => Array(n).fill(false));
15+
const atlantic = Array.from({ length: m }, () => Array(n).fill(false));
16+
17+
const directions = [
18+
[1, 0],
19+
[-1, 0],
20+
[0, 1],
21+
[0, -1],
22+
];
23+
24+
function dfs(r: number, c: number, visited: boolean[][], prevHeight: number) {
25+
if (
26+
r < 0 ||
27+
c < 0 ||
28+
r >= m ||
29+
c >= n ||
30+
visited[r][c] ||
31+
heights[r][c] < prevHeight
32+
)
33+
return;
34+
35+
visited[r][c] = true;
36+
37+
for (const [dr, dc] of directions) {
38+
dfs(r + dr, c + dc, visited, heights[r][c]);
39+
}
40+
}
41+
42+
// 태평양 DFS
43+
for (let i = 0; i < m; i++) {
44+
dfs(i, 0, pacific, heights[i][0]); // 왼쪽
45+
dfs(i, n - 1, atlantic, heights[i][n - 1]); // 오른쪽
46+
}
47+
48+
for (let j = 0; j < n; j++) {
49+
dfs(0, j, pacific, heights[0][j]); // 위쪽
50+
dfs(m - 1, j, atlantic, heights[m - 1][j]); // 아래쪽
51+
}
52+
53+
const result: number[][] = [];
54+
55+
for (let i = 0; i < m; i++) {
56+
for (let j = 0; j < n; j++) {
57+
if (pacific[i][j] && atlantic[i][j]) {
58+
result.push([i, j]);
59+
}
60+
}
61+
}
62+
63+
return result;
64+
}

0 commit comments

Comments
 (0)