2
* @param {number[][]} heights5
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;11
for (let c = 0; c < cols; c++) {12
explore(heights, 0, c, pacific, heights[0][c]); // dfs from top row13
explore(heights, rows - 1, c, atlantic, heights[rows - 1][c]); // dfs from bottom row16
for (let r = 0; r < rows; r++) {17
explore(heights, r, 0, pacific, heights[r][0]); // dfs from left most column18
explore(heights, r, cols - 1, atlantic, heights[r][cols - 1]); // dfs from right most column21
// check if water can flow to both atlantic and pacific ocean.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)) {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;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;44
let pos = r + ',' + c;45
if (visited.has(pos)) return;48
explore(heights, r + 1, c, visited, heights[r][c]) // below49
explore(heights, r - 1, c, visited, heights[r][c]) // above50
explore(heights, r, c + 1, visited, heights[r][c]) // right51
explore(heights, r, c - 1, visited, heights[r][c]) // left