Skip to content

Commit d9f2806

Browse files
committed
feat: Upload pacific-atlantic-water-flow(typescript)
1 parent 4d6f7c4 commit d9f2806

File tree

1 file changed

+75
-0
lines changed

1 file changed

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

0 commit comments

Comments
ย (0)