# x 417. Pacific Atlantic Water Flow

```jsx
/**
 * @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];
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://algorithm.prettylog.com/top-75-leetcode-questions-to-save-your-time/problems/graph/x-417.-pacific-atlantic-water-flow.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
