# 417. Pacific Atlantic Water Flow

Given an `m x n` matrix of non-negative integers representing the height of each unit cell in a continent, the "Pacific ocean" touches the left and top edges of the matrix and the "Atlantic ocean" touches the right and bottom edges.

Water can only flow in four directions (up, down, left, or right) from a cell to another one with height equal or lower.

Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean.

**Note:**<br>

1. The order of returned grid coordinates does not matter.
2. Both m and n are less than 150.

**Example:**

```
Given the following 5x5 matrix:

  Pacific ~   ~   ~   ~   ~ 
       ~  1   2   2   3  (5) *
       ~  3   2   3  (4) (4) *
       ~  2   4  (5)  3   1  *
       ~ (6) (7)  1   4   5  *
       ~ (5)  1   1   2   4  *
          *   *   *   *   * Atlantic

Return:

[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with parentheses in above matrix).
```

```cpp
// DFS Recursion
void helper(vector<vector<int> >& matrix, int i, int j, vector<vector<bool> >& visited, int pre_val) {
    if (i < 0 || i >= matrix.size() || j < 0 || j >= matrix[0].size() || matrix[i][j] < pre_val || visited[i][j]) return;
    visited[i][j] = true;
    helper(matrix, i + 1, j, visited, matrix[i][j]);
    helper(matrix, i - 1, j, visited, matrix[i][j]);
    helper(matrix, i, j + 1, visited, matrix[i][j]);
    helper(matrix, i, j - 1, visited, matrix[i][j]);
}
vector<vector<int>> pacificAtlantic(vector<vector<int>>& matrix) { // time: O(m * n); space: O(m * n)
    vector<vector<int> > res;
    if (matrix.empty() || matrix[0].empty()) return res;
    int m = matrix.size(), n = matrix[0].size();
    vector<vector<bool> > pacific(m, vector<bool>(n, false)), atlantic = pacific;
    // Starts from the boundaries
    for (int i = 0; i < m; ++i) {
        helper(matrix, i, 0, pacific, 0); // left
        helper(matrix, i, n - 1, atlantic, 0); // right
    }
    for (int j = 0; j < n; ++j) {
        helper(matrix, 0, j, pacific, 0); // top
        helper(matrix, m - 1, j, atlantic, 0); // bottom
    }
    // Find the union of pacific and atlantic
    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            if (pacific[i][j] && atlantic[i][j]) 
                res.push_back({i, j});
        }
    }
    return res;
}
```

```cpp
// DFS
void dfs(vector<vector<int> >& matrix, vector<vector<int> >& visited, int pre, int x, int y, int preval) {
    if (x < 0 || x >= matrix.size() || y < 0 || y >= matrix[0].size() || matrix[x][y] < pre || (visited[x][y] & preval)) return;
    visited[x][y] |= preval;
    dfs(matrix, visited, matrix[x][y], x + 1, y, preval);
    dfs(matrix, visited, matrix[x][y], x - 1, y, preval);
    dfs(matrix, visited, matrix[x][y], x, y + 1, preval);
    dfs(matrix, visited, matrix[x][y], x, y - 1, preval);
}
vector<vector<int>> pacificAtlantic(vector<vector<int>>& matrix) { // time: O(m * n); space: O(m * n)
    vector<vector<int> > res;
    if (matrix.empty() || matrix[0].empty()) return res;
    int m = matrix.size(), n = matrix[0].size();
    vector<vector<int> > visited(m, vector<int>(n, 0));
    for (int i = 0; i < m; ++i) {
        dfs(matrix, visited, INT_MIN, i, 0, 1); // pacific
        dfs(matrix, visited, INT_MIN, i, n - 1, 2); // atlantic
    }
    for (int j = 0; j < n; ++j) {
        dfs(matrix, visited, INT_MIN, 0, j, 1); // pacific
        dfs(matrix, visited, INT_MIN, m - 1, j, 2); // atlantic
    }
    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            if (visited[i][j] == 3) res.push_back({i, j});
        }
    }
    return res;
}
```

```cpp
// BFS
void bfs(vector<vector<int> >& matrix, vector<vector<bool> >& visited, queue<vector<int> >& q) {
    int m = matrix.size(), n = matrix[0].size();
    vector<vector<int> > dirs({{1, 0}, {-1, 0}, {0, 1}, {0, -1}});
    while (!q.empty()) {
        auto t = q.front(); q.pop();
        for (auto dir : dirs) {
            int x = t[0] + dir[0], y = t[1] + dir[1];
            if (x < 0 || x >= m || y < 0 || y >= n || visited[x][y] || matrix[x][y] < matrix[t[0]][t[1]]) continue;
            visited[x][y] = true;
            q.push({x, y});
        }
    }
}
vector<vector<int>> pacificAtlantic(vector<vector<int>>& matrix) { // time: O(m * n); space: O(m * n)
    vector<vector<int> > res;
    if (matrix.empty() || matrix[0].empty()) return res;
    int m = matrix.size(), n = matrix[0].size();
    queue<vector<int> > q1, q2;
    vector<vector<bool> > pacific(m, vector<bool>(n, false)), atlantic = pacific;
    for (int i = 0; i < m; ++i) {
        q1.push({i, 0});
        q2.push({i, n - 1});
        pacific[i][0] = true;
        atlantic[i][n - 1] = true;
    }
    for (int j = 0; j < n; ++j) {
        q1.push({0, j});
        q2.push({m - 1, j});
        pacific[0][j] = true;
        atlantic[m - 1][j] = true;
    }
    bfs(matrix, pacific, q1);
    bfs(matrix, atlantic, q2);
    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            if (pacific[i][j] && atlantic[i][j]) res.push_back({i, j});
        }
    }
    return res;
}
```


---

# 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://jimmylin1991.gitbook.io/practice-of-algorithm-problems/dfs-and-bfs/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.
