← Back to Codes

2026-06-09 16:36:42

Pacific Atlantic Water Flow in Python and Java | LeetCode #417

Learn how to solve Pacific Atlantic Water Flow in Python and Java with beginner-friendly explanation, step-by-step dry run, custom examples, and time complexity.

Pacific Atlantic Water Flow in Python and Java

In this tutorial, we will learn LeetCode #417: Pacific Atlantic Water Flow in very simple language. We will understand the idea step by step, see custom examples, and write complete code in Python and Java.

What Is the Pacific Atlantic Water Flow Problem?

This problem asks us to solve a common coding interview task using the given input. The goal is to return the correct result without using a slow brute force method.

For this problem, we will use depth first search from oceans because it gives a clean and optimized solution.

Example input:
heights = [[1,3,2],[4,2,5],[3,6,4]]

Expected result:
Output: cells reaching both oceans

Explanation:
DFS starts from ocean borders.

Beginner-Friendly Idea

The main idea is to avoid trying every possible answer blindly. Instead, we keep useful information while reading the input and use that information to make the next decision.

At each step, ask: “What do I already know, and how does the current value change my answer?”

Using our example:
heights = [[1,3,2],[4,2,5],[3,6,4]]

Approach:
depth first search from oceans

We update variables step by step until we reach:
Output: cells reaching both oceans

Why Do We Use This Approach?

A direct brute force solution is usually easier to think about, but it can become slow when the input is large. The optimized approach keeps only the important state and avoids repeated work.

That is why depth first search from oceans is useful for this problem.

Step-by-Step Explanation

Let us dry run the algorithm using a custom example.

Step 1
Use this custom example.

heights = [[1,3,2],[4,2,5],[3,6,4]]

We will solve it using depth first search from oceans.

Step 2
Look at the first important value from the example and create the variables needed by the algorithm.

current_state = based on the first value
answer = not finished yet

Step 3
Move to the next useful value and update the state.

The algorithm compares the new value with the old state.
If the new value improves the answer, we update the answer.

Step 4
Continue this process until all useful values are processed.

After processing the example, we get:

Output: cells reaching both oceans

Why?
DFS starts from ocean borders.

Important Code Logic

The most important part is updating the algorithm state after reading each useful value. This is where the answer becomes better step by step.

Think like this:

old_state = what we knew before
current_value = value we are checking now
new_state = updated result after using current_value

For our example, the final state gives:
Output: cells reaching both oceans

Example 1

Input:
heights = [[1,3,2],[4,2,5],[3,6,4]]

Output:
Output: cells reaching both oceans

Explanation:
DFS starts from ocean borders.

Example 2

Input:
heights = [[2,1,3],[3,4,2],[5,1,4]]

Output:
cells reaching both oceans

Explanation:
Water flow is checked from both ocean borders.

Python Code

Here is the complete Python solution for LeetCode #417.

class PacificAtlanticWaterFlowFinder:
    def pacific_atlantic(self, heights):
        rows = len(heights)
        cols = len(heights[0])
        pacific = set()
        atlantic = set()

        def dfs(row, col, visited, previous_height):
            if (row < 0 or col < 0 or row == rows or col == cols or
                (row, col) in visited or heights[row][col] < previous_height):
                return
            visited.add((row, col))
            dfs(row + 1, col, visited, heights[row][col])
            dfs(row - 1, col, visited, heights[row][col])
            dfs(row, col + 1, visited, heights[row][col])
            dfs(row, col - 1, visited, heights[row][col])

        for col in range(cols):
            dfs(0, col, pacific, heights[0][col])
            dfs(rows - 1, col, atlantic, heights[rows - 1][col])
        for row in range(rows):
            dfs(row, 0, pacific, heights[row][0])
            dfs(row, cols - 1, atlantic, heights[row][cols - 1])

        return sorted(list(pacific & atlantic))


finder = PacificAtlanticWaterFlowFinder()
heights = [[3, 3, 4], [2, 5, 3], [1, 2, 4]]
print(finder.pacific_atlantic(heights))  # Output includes cells that can reach both oceans

Java Code

Here is the complete Java solution for LeetCode #417.

import java.util.ArrayList;
import java.util.List;

class PacificAtlanticWaterFlowFinder {
    public List<List<Integer>> pacificAtlantic(int[][] heights) {
        int rows = heights.length;
        int cols = heights[0].length;
        boolean[][] pacific = new boolean[rows][cols];
        boolean[][] atlantic = new boolean[rows][cols];

        for (int col = 0; col < cols; col++) {
            dfs(0, col, pacific, heights);
            dfs(rows - 1, col, atlantic, heights);
        }
        for (int row = 0; row < rows; row++) {
            dfs(row, 0, pacific, heights);
            dfs(row, cols - 1, atlantic, heights);
        }

        List<List<Integer>> result = new ArrayList<>();
        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < cols; col++) {
                if (pacific[row][col] && atlantic[row][col]) {
                    List<Integer> cell = new ArrayList<>();
                    cell.add(row);
                    cell.add(col);
                    result.add(cell);
                }
            }
        }
        return result;
    }

    private void dfs(int row, int col, boolean[][] visited, int[][] heights) {
        visited[row][col] = true;
        int[][] directions = {{1,0}, {-1,0}, {0,1}, {0,-1}};
        for (int[] dir : directions) {
            int nextRow = row + dir[0];
            int nextCol = col + dir[1];
            if (nextRow < 0 || nextCol < 0 || nextRow == heights.length || nextCol == heights[0].length) continue;
            if (visited[nextRow][nextCol] || heights[nextRow][nextCol] < heights[row][col]) continue;
            dfs(nextRow, nextCol, visited, heights);
        }
    }

    public static void main(String[] args) {
        PacificAtlanticWaterFlowFinder finder = new PacificAtlanticWaterFlowFinder();
        int[][] heights = {{3,3,4}, {2,5,3}, {1,2,4}};
        System.out.println(finder.pacificAtlantic(heights));
    }
}

Time and Space Complexity

Time Complexity: O(n)

The time complexity depends on how many values the algorithm needs to process and whether it uses sorting, binary search, heap, or traversal.

Space Complexity: O(n)

The extra space is used for the variables or data structures needed by the optimized approach.

Final Summary

LeetCode #417: Pacific Atlantic Water Flow becomes easier when we break it into small steps. First understand what the problem asks, then track the important state, dry run with an example, and finally write the code.