DSA AnimatorREVISION VIDEOS
← Back to problems
New

Pacific Atlantic Water Flow — LeetCode 417 video explanation

A grid of heights touches the Pacific on its top and left edges, and the Atlantic on its bottom and right edges. Water flows from a cell to a neighbour with equal or lower height. Return every cell from which water can reach both oceans.

Loading videos…

DSA Animator › DSA Revision › Graph › Pacific Atlantic Water Flow

Key moments in the Pacific Atlantic Water Flow video

0:06Problem0:21Example0:32Brute force0:43Key idea1:02Dry run1:26Code1:45Takeaway

What you will learn

Remember: when many sources ask the same question, search backwards from the targets. Flowing down becomes climbing up. The video solves Pacific Atlantic Water Flow (LeetCode 417, Medium) with the Reverse Multi-Source DFS pattern from the Graph topic, and you can replay every step in the interactive Pacific Atlantic Water Flow animation.

Pacific Atlantic Water Flow video transcript

Problem

A grid of heights touches the Pacific on its top and left edges, and the Atlantic on its bottom and right edges. Water flows from a cell to a neighbour with equal or lower height. Return every cell from which water can reach both oceans.

Example

For the classic 5 by 5 grid, seven cells can reach both oceans. They are 0 4, 1 3, 1 4, 2 2, 3 0, 3 1 and 4 0.

Brute force

Starting a search from every single cell, and checking whether it reaches each ocean, repeats the same work again and again. That is O of the grid size squared.

Key idea

Turn the question around, and let water climb up from the oceans instead. From the Pacific edges, move to neighbours that are equal or higher, and mark everything you reach. Do the same from the Atlantic edges with a second marking. A cell reachable in both searches can drain into both oceans.

Dry run

Start the Pacific search from the top row and the left column. Climbing uphill marks 16 cells, mostly in the top left part. Start the Atlantic search from the bottom row and the right column. It also marks 16 cells, mostly in the bottom right part. The cells marked by both are the answer. There are seven of them, including the peak of height 5 in the centre.

Code

In code, keep two boolean grids, one for each ocean. Run a DFS from every edge cell of each ocean. The DFS moves to a neighbour only if it is inside the grid, not visited, and at least as high. Collect cells true in both grids, so it's O of rows times columns.

Takeaway

Remember: when many sources ask the same question, search backwards from the targets. Flowing down becomes climbing up.

More Graph revision videos

← All 185 DSA revision videos