x 417. Pacific Atlantic Water Flow
/**
* @param {number[][]} heights
* @return {number[][]}
*/
let memo;
var pacificAtlantic = function (heights) {
memo = new Array(heights.length);
for (let i = 0; i < heights.length; i++) {
memo[i] = new Array(heights[0].length).fill(0);
}
const answer = [];
for (let i = 0; i < heights.length; i++) {
for (let j = 0; j < heights[0].length; j++) {
const [f, s] = traverse(heights, memo, i, j);
if (f && s) {
memo[i][j] = 1;
answer.push([i, j]);
} else {
memo[i][j] = -1;
}
}
}
return answer;
};
function traverse(m, memo, row, col, prev = 100001) {
if (row < 0 || col < 0) {
return [true, false];
}
if (row >= m.length || col >= m[0].length) {
return [false, true];
}
const curr = m[row][col];
if (curr < 0) return [false, false];
if (curr > prev) return [false, false];
if (memo[row][col] === 1) return [true, true];
m[row][col] -= 200000;
const left = traverse(m, memo, row, col - 1, curr);
const up = traverse(m, memo, row - 1, col, curr);
const right = traverse(m, memo, row, col + 1, curr);
const down = traverse(m, memo, row + 1, col, curr);
m[row][col] += 200000;
const pacific = left[0] || up[0] || right[0] || down[0];
const atlantic = left[1] || up[1] || right[1] || down[1];
return [pacific, atlantic];
}
Last updated