Skip to content
Problem 417 · LeetCode 417(opens in a new tab)

Pacific Atlantic Water Flow

MediumGraphs

A rectangular island is split into cells, and heights[r][c] is the height of the cell in row r, column c. The Pacific Ocean runs along the top and left edges of the island; the Atlantic runs along the bottom and right edges.

Rain on a cell runs to a neighbour above, below, left or right when that neighbour is no higher. From any cell on an edge, it runs straight into that edge's ocean.

Return the coordinates [r, c] of every cell whose rain can reach both oceans, in any order.

Example 1

Input:  heights = [[1, 2, 2],
                   [4, 6, 3],
                   [2, 1, 1]]
Output: [[0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0]]
Why:    (0, 0) is a dip that only meets the Pacific;
        (2, 1) and (2, 2) only meet the Atlantic
2 more examples and the constraints

Example 2

Input:  heights = [[42]]
Output: [[0, 0]]
Why:    the one cell touches every edge

Example 3

Input:  heights = [[1, 3],
                   [2, 4]]
Output: [[0, 1], [1, 0], [1, 1]]
Why:    rain on the 1 cannot climb to the right or bottom edge

Constraints

  • 1 ≤ rows, columns ≤ 200
  • 0 ≤ each height ≤ 100,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Follow the rain from every cellO((m·n)²)
  2. Climb up from each oceanO(m·n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for a 200 × 200 gridVerdict
Follow the rain from every cellO((m·n)²)
Mention it, then move on
Climb up from each oceanO(m·n)
Best; two searches in total

m = rows, n = columns.

Edge cases to test

  • One cell. [[42]] touches all four edges, so it reaches both oceans.
  • One row or one column. Every cell touches both a Pacific edge and an Atlantic edge.
  • Flat ground. Equal heights let water run sideways, so every cell qualifies; the test must be ≥, not >.
  • A pit. A low cell boxed in by higher ones reaches no ocean at all.

Common mistakes

  • Climbing from the ocean with "neighbour ≤ current", which runs the water downhill twice.
  • Using > instead of ≥, so water stops on level ground.
  • Forgetting the corner cells belong to two edges, or seeding the Atlantic from the top row.

How to talk through it

  1. 1Clarify. Does water flow onto equal heights? Which edges belong to which ocean? Any order for the output?
  2. 2Give the brute force. A downhill search from every cell: O((m·n)²), and say what it repeats.
  3. 3Reverse the flow. Search from the oceans uphill instead: two searches cover every cell.
  4. 4Code one helper. A BFS that takes its start cells and returns the marked grid; call it twice.
  5. 5Test out loud. Run one cell, flat ground and a pit before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?