Skip to content

Commit bfd79dd

Browse files
committed
add solution : 417. Pacific Atlantic Water Flow
1 parent 3045f60 commit bfd79dd

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
/**
2+
* @link https://leetcode.com/problems/pacific-atlantic-water-flow/description/
3+
*
4+
* ์ ‘๊ทผ ๋ฐฉ๋ฒ• :
5+
* - pacific, atlantic๋ฅผ ๋™์‹œ์— ๋„๋‹ฌํ•˜๋Š” ์ง€์  ์ฐพ๊ธฐ ์œ„ํ•ด์„œ, ๋„๋‹ฌ ์—ฌ๋ถ€ ํŠธ๋ž˜ํ‚นํ•˜๋Š” 2๊ฐœ์˜ visited ๋ฐฐ์—ด ์‚ฌ์šฉํ•œ๋‹ค.
6+
* - ๋ฐ”๋‹ค ๊ฒฝ๊ณ„์—์„œ๋งŒ DFS๋ฅผ ํ˜ธ์ถœํ•ด์„œ ๋ฐฉ๋ฌธ ์—ฌ๋ถ€ ์ฒดํฌํ•œ๋‹ค.
7+
* - ๋ฐ”๋‹ค ๊ฒฝ๊ณ„์—์„œ ์‹œ์ž‘ํ–ˆ๊ธฐ ๋•Œ๋ฌธ์— DFS๋Š” ์ธ์ ‘ ์…€์˜ ๋†’์ด๊ฐ€ ๊ฐ™๊ฑฐ๋‚˜ ๋†’์„ ๋•Œ๋งŒ ํ˜ธ์ถœ๋˜์–ด์•ผ ํ•œ๋‹ค.
8+
*
9+
* ์‹œ๊ฐ„๋ณต์žก๋„ : O(m * n)
10+
* - ๊ฐ ์…€๋งˆ๋‹ค ์ตœ๋Œ€ 4๋ฒˆ DFS๊ฐ€ ํ˜ธ์ถœ๋  ์ˆ˜ ์žˆ๋‹ค. O(m * n)
11+
* - ๊ฒฐ๊ณผ ์ˆœํšŒํ•  ๋•Œ m * n ๋งŒํผ ์ˆœํšŒํ•œ๋‹ค.
12+
*
13+
* ๊ณต๊ฐ„๋ณต์žก๋„ : O(m * n)
14+
* - 2๊ฐœ์˜ visited ๋ฐฐ์—ด ์‚ฌ์šฉํ•œ๋‹ค.
15+
* - ์ตœ์•…์˜ ๊ฒฝ์šฐ, m * n ๋ชจ๋“  ์นธ์—์„œ DFS ํ˜ธ์ถœ๋œ๋‹ค.
16+
*/
17+
18+
const directions = [
19+
[-1, 0],
20+
[1, 0],
21+
[0, -1],
22+
[0, 1],
23+
];
24+
25+
function pacificAtlantic(heights: number[][]): number[][] {
26+
const result: number[][] = [];
27+
28+
const rows = heights.length;
29+
const cols = heights[0].length;
30+
31+
// ๋‘ ๋ฐ”๋‹ค ๋„๋‹ฌํ•˜๋Š” ์ง€์  ํŠธ๋ž˜ํ‚น ํ•˜๊ธฐ ์œ„ํ•œ ๋ฐฐ์—ด
32+
const pacificVisited = Array.from({ length: rows }, () =>
33+
Array(cols).fill(false)
34+
);
35+
const atlanticVisited = Array.from({ length: rows }, () =>
36+
Array(cols).fill(false)
37+
);
38+
39+
const dfs = (row: number, col: number, visited: boolean[][]) => {
40+
if (visited[row][col]) return;
41+
// ๋ฐฉ๋ฌธ ์ง€์  ๊ธฐ๋ก
42+
visited[row][col] = true;
43+
44+
for (const [x, y] of directions) {
45+
const newRow = row + x;
46+
const newCol = col + y;
47+
48+
// ์ƒˆ๋กœ์šด ์œ„์น˜๊ฐ€ ๊ฒฝ๊ณ„์•ˆ์— ์žˆ๊ณ , ํ˜„์žฌ ๋†’์ด๋ณด๋‹ค ๊ฐ™๊ฑฐ๋‚˜ ๋†’์„ ๋•Œ๋งŒ DFS ํ˜ธ์ถœ
49+
if (
50+
0 <= newRow &&
51+
newRow < rows &&
52+
0 <= newCol &&
53+
newCol < cols &&
54+
heights[newRow][newCol] >= heights[row][col]
55+
)
56+
dfs(newRow, newCol, visited);
57+
}
58+
};
59+
60+
// pacific ๊ฒฝ๊ณ„์—์„œ DFS ํ˜ธ์ถœ (์ฒซ ๋ฒˆ์จฐ ์—ด, ์ฒซ ๋ฒˆ์งธ ํ–‰)
61+
for (let row = 0; row < rows; row++) dfs(row, 0, pacificVisited);
62+
for (let col = 0; col < cols; col++) dfs(0, col, pacificVisited);
63+
64+
// atlantic ๊ฒฝ๊ณ„์—์„œ DFS ํ˜ธ์ถœ (๋งˆ์ง€๋ง‰ ์—ด, ๋งˆ์ง€๋ง‰ ํ–‰)
65+
for (let row = 0; row < rows; row++) dfs(row, cols - 1, atlanticVisited);
66+
for (let col = 0; col < cols; col++) dfs(rows - 1, col, atlanticVisited);
67+
68+
for (let row = 0; row < rows; row++) {
69+
for (let col = 0; col < cols; col++) {
70+
if (pacificVisited[row][col] && atlanticVisited[row][col])
71+
result.push([row, col]);
72+
}
73+
}
74+
75+
return result;
76+
}

0 commit comments

Comments
ย (0)