Pacific Atlantic Water Flow

MediumGraphDFSMatrixMulti-Source DFS
Category: Graphs
Companies that ask this question:
AmazonGoogleFacebookMicrosoftUber

Approach

Pacific Atlantic Water Flow

Problem Statement

There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches the island's right and bottom edges.

The island is partitioned into a grid of square cells. You are given an m x n integer matrix heights where heights[r][c] represents the height above sea level of the cell at coordinate (r, c).

The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is less than or equal to the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean.

Return a 2D list of grid coordinates result where result[i] = [ri, ci] denotes that rain water can flow from cell (ri, ci) to both the Pacific and Atlantic oceans.

Examples

Example 1:

Input: heights = [
  [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]
]
Output: [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]
Explanation: These cells can flow to both oceans.

Example 2:

Input: heights = [[1]]
Output: [[0,0]]
Explanation: The water can flow to both oceans from the only cell.

Constraints

  • m == heights.length
  • n == heights[r].length
  • 1 <= m, n <= 200
  • 0 <= heights[r][c] <= 10^5

Approach: Multi-Source DFS

Use multi-source DFS from both oceans to find cells reachable from each ocean, then find the intersection.

Algorithm:

  1. Create two boolean matrices for Pacific and Atlantic reachability
  2. DFS from all Pacific Ocean edges (top and left)
  3. DFS from all Atlantic Ocean edges (bottom and right)
  4. Water flows from cell to neighbor if neighbor height >= current height
  5. Find cells reachable from both oceans (intersection)

Time Complexity: O(m × n) - visit each cell at most twice (once per ocean) Space Complexity: O(m × n) - for the boolean matrices and recursion stack

Solution

java
1import java.util.*;
2
3class Solution {
4    public List<List<Integer>> pacificAtlantic(int[][] heights) {
5        List<List<Integer>> result = new ArrayList<>();
6        if (heights == null || heights.length == 0) return result;
7
8        int m = heights.length;
9        int n = heights[0].length;
10        boolean[][] pacific = new boolean[m][n];
11        boolean[][] atlantic = new boolean[m][n];
12
13        // DFS from Pacific Ocean (top and left edges)
14        for (int i = 0; i < m; i++) {
15            dfs(heights, pacific, i, 0, m, n);
16        }
17        for (int j = 0; j < n; j++) {
18            dfs(heights, pacific, 0, j, m, n);
19        }
20
21        // DFS from Atlantic Ocean (bottom and right edges)
22        for (int i = 0; i < m; i++) {
23            dfs(heights, atlantic, i, n - 1, m, n);
24        }
25        for (int j = 0; j < n; j++) {
26            dfs(heights, atlantic, m - 1, j, m, n);
27        }
28
29        // Find cells that can reach both oceans
30        for (int i = 0; i < m; i++) {
31            for (int j = 0; j < n; j++) {
32                if (pacific[i][j] && atlantic[i][j]) {
33                    result.add(Arrays.asList(i, j));
34                }
35            }
36        }
37
38        return result;
39    }
40
41    private void dfs(int[][] heights, boolean[][] ocean, int i, int j, int m, int n) {
42        // Already visited
43        if (ocean[i][j]) return;
44
45        ocean[i][j] = true;
46
47        int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
48        for (int[] dir : directions) {
49            int ni = i + dir[0];
50            int nj = j + dir[1];
51
52            // Check boundaries and water flow (neighbor height >= current height)
53            if (ni >= 0 && ni < m && nj >= 0 && nj < n &&
54                heights[ni][nj] >= heights[i][j]) {
55                dfs(heights, ocean, ni, nj, m, n);
56            }
57        }
58    }
59}
60
61/**
62 * Time Complexity: O(m * n)
63 * - We visit each cell at most twice (once for each ocean)
64 *
65 * Space Complexity: O(m * n)
66 * - Two boolean matrices + recursion stack
67 *
68 * Key Insights:
69 * - Work backwards: find cells reachable TO each ocean FROM the edges
70 * - Water flows from high to low or equal height
71 * - Multi-source DFS from ocean edges
72 * - Intersection of reachable sets gives answer
73 */
74
Loading visualizer...