1
`/**
2
* @param {number[][]} heights
3
* @return {number[][]}
4
*/
5
var pacificAtlantic = function(heights) {
6
let atlantic = new Set();
7
let pacific = new Set();
8
let rows = heights.length;
9
let cols = heights[0].length;
10

11
for (let c = 0; c < cols; c++) {
12
explore(heights, 0, c, pacific, heights[0][c]); // dfs from top row
13
explore(heights, rows - 1, c, atlantic, heights[rows - 1][c]); // dfs from bottom row
14
}
15

16
for (let r = 0; r < rows; r++) {
17
explore(heights, r, 0, pacific, heights[r][0]); // dfs from left most column
18
explore(heights, r, cols - 1, atlantic, heights[r][cols - 1]); // dfs from right most column
19
}
20

21
// check if water can flow to both atlantic and pacific ocean.
22
let res = [];
23
for (let r = 0; r < rows; r++) {
24
for (let c = 0; c < cols; c++) {
25
let pos = r + ',' + c;
26
if (atlantic.has(pos) && pacific.has(pos)) {
27
res.push([r, c]);
28
}
29
}
30
}
31

32
return res;
33
};
34

35
function explore(heights, r, c, visited, prevHeight) {
36
let rowInbound = 0 <= r && r < heights.length;
37
let colInbound = 0 <= c && c < heights[0].length;
38
if (!rowInbound || !colInbound) return;
39

40
// height must be higher than prev height. water can only flow downwards not upwards. duh.
41
// if it's the first value then it's just the same value so it's not less than so it will not return.
42
if (heights[r][c] < prevHeight) return;
43

44
let pos = r + ',' + c;
45
if (visited.has(pos)) return;
46
visited.add(pos)
47

48
explore(heights, r + 1, c, visited, heights[r][c]) // below
49
explore(heights, r - 1, c, visited, heights[r][c]) // above
50
explore(heights, r, c + 1, visited, heights[r][c]) // right
51
explore(heights, r, c - 1, visited, heights[r][c]) // left
52
}`;

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0