Skip to content

Commit 73c3f0d

Browse files
committed
pacific-atlantic-water-flow solution
1 parent 8705c4e commit 73c3f0d

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* @param {number[][]} heights
3+
* @return {number[][]}
4+
*/
5+
const pacificAtlantic = (heights) => {
6+
const m = heights.length;
7+
const n = heights[0].length;
8+
const pacific = Array.from({ length: m }, () => Array(n).fill(false));
9+
const atlantic = Array.from({ length: m }, () => Array(n).fill(false));
10+
11+
const dfs = (r, c, visited, prevHeight) => {
12+
if (
13+
r < 0 || c < 0 || r >= m || c >= n ||
14+
visited[r][c] || heights[r][c] < prevHeight
15+
) return;
16+
17+
visited[r][c] = true;
18+
19+
dfs(r + 1, c, visited, heights[r][c]);
20+
dfs(r - 1, c, visited, heights[r][c]);
21+
dfs(r, c + 1, visited, heights[r][c]);
22+
dfs(r, c - 1, visited, heights[r][c]);
23+
};
24+
25+
for (let i = 0; i < m; i++) {
26+
dfs(i, 0, pacific, heights[i][0]);
27+
dfs(i, n - 1, atlantic, heights[i][n - 1]);
28+
}
29+
30+
for (let j = 0; j < n; j++) {
31+
dfs(0, j, pacific, heights[0][j]);
32+
dfs(m - 1, j, atlantic, heights[m - 1][j]);
33+
}
34+
35+
const result = [];
36+
for (let i = 0; i < m; i++) {
37+
for (let j = 0; j < n; j++) {
38+
if (pacific[i][j] && atlantic[i][j]) {
39+
result.push([i, j]);
40+
}
41+
}
42+
}
43+
return result;
44+
};

0 commit comments

Comments
 (0)