##### Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/417.html

# 417. Pacific Atlantic Water Flow

Medium

## Description

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:

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).

## Solution

Since water can only flow from a cell to another one with height equal or lower, think of the solution in the opposite direction. Starting from the “Pacific ocean” and the “Atlantic ocean” respectively, find the cells from which water can flow to the oceans. If a cell A can make water flow to the ocean, then consider the adjacent cells of A. If a cell is adjacent to A and has an equal or higher height, then water can flow from the cell to A, and thus water can flow from the cell to the ocean.

For both “Pacific ocean” and “Atlantic ocean”, use the idea of breadth first search and for each cell, determine whether water can flow to the ocean starting from the cell.

If a cell can make water flow to both oceans, add it to the result list.

• class Solution {
public List<List<Integer>> pacificAtlantic(int[][] matrix) {
List<List<Integer>> list = new ArrayList<List<Integer>>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
return list;
int rows = matrix.length, columns = matrix[0].length;
boolean[][] pacificFlows = new boolean[rows][columns];
boolean[][] atlanticFlows = new boolean[rows][columns];
for (int i = 0; i < rows; i++) {
pacificFlows[i][0] = true;
pacificQueue.offer(new int[]{i, 0});
}
for (int i = 1; i < columns; i++) {
pacificFlows[0][i] = true;
pacificQueue.offer(new int[]{0, i});
}
for (int i = 0; i < rows; i++) {
atlanticFlows[i][columns - 1] = true;
atlanticQueue.offer(new int[]{i, columns - 1});
}
for (int i = 0; i < columns - 1; i++) {
atlanticFlows[rows - 1][i] = true;
atlanticQueue.offer(new int[]{rows - 1, i});
}
int[][] directions = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
while (!pacificQueue.isEmpty()) {
int[] cell = pacificQueue.poll();
int row = cell[0], column = cell[1];
int height = matrix[row][column];
for (int[] direction : directions) {
int newRow = row + direction[0], newColumn = column + direction[1];
if (newRow >= 0 && newRow < rows && newColumn >= 0 && newColumn < columns) {
if (matrix[newRow][newColumn] >= height && !pacificFlows[newRow][newColumn]) {
pacificFlows[newRow][newColumn] = true;
pacificQueue.offer(new int[]{newRow, newColumn});
}
}
}
}
while (!atlanticQueue.isEmpty()) {
int[] cell = atlanticQueue.poll();
int row = cell[0], column = cell[1];
int height = matrix[row][column];
for (int[] direction : directions) {
int newRow = row + direction[0], newColumn = column + direction[1];
if (newRow >= 0 && newRow < rows && newColumn >= 0 && newColumn < columns) {
if (matrix[newRow][newColumn] >= height && !atlanticFlows[newRow][newColumn]) {
atlanticFlows[newRow][newColumn] = true;
atlanticQueue.offer(new int[]{newRow, newColumn});
}
}
}
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
if (pacificFlows[i][j] && atlanticFlows[i][j]) {
List<Integer> coordinate = new ArrayList<Integer>();
}
}
}
return list;
}
}

############

class Solution {
private int[][] heights;
private int m;
private int n;

public List<List<Integer>> pacificAtlantic(int[][] heights) {
m = heights.length;
n = heights[0].length;
this.heights = heights;
Set<Integer> vis1 = new HashSet<>();
Set<Integer> vis2 = new HashSet<>();
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (i == 0 || j == 0) {
q1.offer(new int[] {i, j});
}
if (i == m - 1 || j == n - 1) {
q2.offer(new int[] {i, j});
}
}
}
bfs(q1, vis1);
bfs(q2, vis2);
List<List<Integer>> ans = new ArrayList<>();
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
int x = i * n + j;
if (vis1.contains(x) && vis2.contains(x)) {
}
}
}
return ans;
}

private void bfs(Deque<int[]> q, Set<Integer> vis) {
int[] dirs = {-1, 0, 1, 0, -1};
while (!q.isEmpty()) {
for (int k = q.size(); k > 0; --k) {
int[] p = q.poll();
for (int i = 0; i < 4; ++i) {
int x = p[0] + dirs[i];
int y = p[1] + dirs[i + 1];
if (x >= 0 && x < m && y >= 0 && y < n && !vis.contains(x * n + y)
&& heights[x][y] >= heights[p[0]][p[1]]) {
q.offer(new int[] {x, y});
}
}
}
}
}
}

• // OJ: https://leetcode.com/problems/pacific-atlantic-water-flow/
// Time: O(MN)
// Space: O(MN)
class Solution {
int dirs[4][2] = { {0,1},{0,-1},{1,0},{-1,0} }, M, N;
void dfs(vector<vector<int>> &A, int x, int y, vector<vector<int>> &m) {
if (m[x][y]) return;
m[x][y] = 1;
for (auto &[dx, dy] : dirs) {
int a = x + dx, b = y + dy;
if (a < 0 || a >= M || b < 0 || b >= N || A[a][b] < A[x][y]) continue;
dfs(A, a, b, m);
}
}
public:
vector<vector<int>> pacificAtlantic(vector<vector<int>>& A) {
if (A.empty() || A[0].empty()) return {};
M = A.size(), N = A[0].size();
vector<vector<int>> a(M, vector<int>(N)), b(M, vector<int>(N)), ans;
for (int i = 0; i < M; ++i) {
dfs(A, i, 0, a);
dfs(A, i, N - 1, b);
}
for (int j = 0; j < N; ++j) {
dfs(A, 0, j, a);
dfs(A, M - 1, j, b);
}
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
if (a[i][j] && b[i][j]) ans.push_back({i, j});
}
}
return ans;
}
};

• class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
def bfs(q, vis):
while q:
for _ in range(len(q)):
i, j = q.popleft()
for a, b in [[0, -1], [0, 1], [1, 0], [-1, 0]]:
x, y = i + a, j + b
if (
0 <= x < m
and 0 <= y < n
and (x, y) not in vis
and heights[x][y] >= heights[i][j]
):
q.append((x, y))

m, n = len(heights), len(heights[0])
vis1, vis2 = set(), set()
q1 = deque()
q2 = deque()
for i in range(m):
for j in range(n):
if i == 0 or j == 0:
q1.append((i, j))
if i == m - 1 or j == n - 1:
q2.append((i, j))
bfs(q1, vis1)
bfs(q2, vis2)
return [
(i, j)
for i in range(m)
for j in range(n)
if (i, j) in vis1 and (i, j) in vis2
]

############

class Solution(object):
def pacificAtlantic(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
if not matrix:
return []
n, m = len(matrix), len(matrix[0])
pacific = set()
atlantic = set()
ans = []

def dfs(matrix, visited, i, j):
visited |= {(i, j)}
for di, dj in [(0, -1), (0, 1), (-1, 0), (1, 0)]:
ni, nj = i + di, j + dj
if 0 <= ni < n and 0 <= nj < m and (ni, nj) not in visited:
if matrix[ni][nj] >= matrix[i][j]:
dfs(matrix, visited, ni, nj)

for i in range(n):
dfs(matrix, pacific, i, 0)
dfs(matrix, atlantic, i, m - 1)
for j in range(m):
dfs(matrix, pacific, 0, j)
dfs(matrix, atlantic, n - 1, j)
return list(pacific & atlantic)

• func pacificAtlantic(heights [][]int) [][]int {
m, n := len(heights), len(heights[0])
vis1 := make(map[int]bool)
vis2 := make(map[int]bool)
var q1 [][]int
var q2 [][]int
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if i == 0 || j == 0 {
vis1[i*n+j] = true
q1 = append(q1, []int{i, j})
}
if i == m-1 || j == n-1 {
vis2[i*n+j] = true
q2 = append(q2, []int{i, j})
}
}
}
dirs := []int{-1, 0, 1, 0, -1}
bfs := func(q [][]int, vis map[int]bool) {
for len(q) > 0 {
for k := len(q); k > 0; k-- {
p := q[0]
q = q[1:]
for i := 0; i < 4; i++ {
x, y := p[0]+dirs[i], p[1]+dirs[i+1]
if x >= 0 && x < m && y >= 0 && y < n && !vis[x*n+y] && heights[x][y] >= heights[p[0]][p[1]] {
vis[x*n+y] = true
q = append(q, []int{x, y})
}
}
}
}
}
bfs(q1, vis1)
bfs(q2, vis2)
var ans [][]int
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
x := i*n + j
if vis1[x] && vis2[x] {
ans = append(ans, []int{i, j})
}
}
}
return ans
}

• function pacificAtlantic(heights: number[][]): number[][] {
const m = heights.length;
const n = heights[0].length;
const dirs = [
[1, 0],
[0, 1],
[-1, 0],
[0, -1],
];
const gird = new Array(m).fill(0).map(() => new Array(n).fill(0));
const isVis = new Array(m).fill(0).map(() => new Array(n).fill(false));

const dfs = (i: number, j: number) => {
if (isVis[i][j]) {
return;
}
gird[i][j]++;
isVis[i][j] = true;
const h = heights[i][j];
for (const [x, y] of dirs) {
if (h <= (heights[i + x] ?? [])[j + y]) {
dfs(i + x, j + y);
}
}
};

for (let i = 0; i < n; i++) {
dfs(0, i);
}
for (let i = 0; i < m; i++) {
dfs(i, 0);
}
isVis.forEach(v => v.fill(false));
for (let i = 0; i < n; i++) {
dfs(m - 1, i);
}
for (let i = 0; i < m; i++) {
dfs(i, n - 1);
}

const res = [];
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (gird[i][j] === 2) {
res.push([i, j]);
}
}
}
return res;
}