Skip to content

Commit 6838953

Browse files
committed
Added pacificAtlanticWaterFlow solution
1 parent 9df4c39 commit 6838953

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/**
2+
* @param {number[][]} heights
3+
* @return {number[][]}
4+
*/
5+
var pacificAtlantic = function (heights) {
6+
const m = heights.length,
7+
n = heights[0].length;
8+
let result = [];
9+
10+
const pacific = new Array(m).fill(null).map(() => new Array(n).fill(false));
11+
const atlantic = new Array(m).fill(null).map(() => new Array(n).fill(false));
12+
13+
const dir = [
14+
[0, 1],
15+
[1, 0],
16+
[0, -1],
17+
[-1, 0],
18+
];
19+
20+
const dfs = (i, j, ocean) => {
21+
// Check visited cell
22+
ocean[i][j] = true;
23+
24+
for (d of dir) {
25+
let x = i + d[0],
26+
y = j + d[1];
27+
if (
28+
x >= 0 &&
29+
x < m &&
30+
y >= 0 &&
31+
y < n &&
32+
!ocean[x][y] &&
33+
heights[x][y] >= heights[i][j]
34+
) {
35+
dfs(x, y, ocean);
36+
}
37+
}
38+
};
39+
40+
// Check the cells can flow left and right edge
41+
for (let i = 0; i < m; i++) {
42+
dfs(i, 0, pacific);
43+
dfs(i, n - 1, atlantic);
44+
}
45+
46+
// Check the cells can flow top and bottom edge
47+
for (let j = 0; j < n; j++) {
48+
dfs(0, j, pacific);
49+
dfs(m - 1, j, atlantic);
50+
}
51+
52+
for (let i = 0; i < m; i++) {
53+
for (let j = 0; j < n; j++) {
54+
if (pacific[i][j] && atlantic[i][j]) {
55+
result.push([i, j]);
56+
}
57+
}
58+
}
59+
return result;
60+
};
61+
62+
// TC: O(m*n)
63+
// SC: O(m*n)

0 commit comments

Comments
 (0)