hardGraphsBinary SearchBinary Search

Swim in Rising Water

hardTime: O(n^2 log n)Space: O(n^2)

Recognize the pattern

minimum time to reach bottom-rightgrid with elevationbinary search on time + BFS

Brute force idea

If you approach Swim in Rising Water in the most literal way possible, you get this: Try all paths and find the minimum maximum elevation — exponential path enumeration. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

Better approach

A calmer way to see Swim in Rising Water is this: Binary search on the answer (time t): for each candidate t, check if you can reach (n-1,n-1) using only cells with elevation ≤ t (BFS/DFS). The minimum t where a path exists is the answer. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

Key invariant

The truth you want to protect throughout Swim in Rising Water is this: If you can swim at time t (all cells ≤ t are passable), you can also swim at time t+1. This monotonicity makes binary search valid. The feasibility check is a simple grid BFS. If that remains true after every update, the rest of the reasoning has a stable place to stand.

Watch out for

The trap in Swim in Rising Water usually looks like this: Using Dijkstra when binary search + BFS is simpler. Both work, but binary search on the answer with a BFS check is easier to implement and reason about. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Binary Search Pattern