Problem Statement

Swim in Rising Water

You have an n x n grid of numbers. Each number is the height of the ground at that spot. Now it starts to rain, and water rises over time. At time t, the water level is t. You can step from one cell to a neighbor (up, down, left, or right) only if both cells are at or below the water level, that is both heights are <= t. You start at the top-left corner and want to reach the bottom-right corner. The question is, what is the smallest time t at which a path from start to finish exists? Higher t means more of the grid is underwater and walkable, so we want the lowest t that still connects start to end.

hardGraphsBinary SearchBinary SearchTime: O(n^2 log n) · Space: O(n^2)

Signals to notice

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

Brute force first

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.

The key insight

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.

Trace it on grid=[[0,2],[1,3]] (n=2, target=(1,1), answer=3)

heap=[(0,0,0)]; pop (cost0,r0,c0)=(0,0,0) -> visit (0,0); not target; push nbrs (1,0)cost=max(0,1)=1, (0,1)cost=max(0,2)=2
heap=[(1,1,0),(2,0,1)]; pop (1,1,0) -> visit (1,0); not target; push (1,1)cost=max(1,3)=3 ; (0,0) already visited
heap=[(2,0,1),(3,1,1)]; pop (2,0,1) -> visit (0,1); not target; push (1,1)cost=max(2,3)=3 ; (0,0) visited
heap=[(3,1,1),(3,1,1)]; pop (3,1,1) -> (r,c)==(n-1,n-1) target reached
return cost = 3

What must stay true

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.

Shape of the loop

heap = min-heap of (cost, r, c) seeded with (grid[0][0], 0, 0)
while heap:
    cost, r, c = pop-min(heap)            # smallest max-elevation path
    if (r,c) seen: continue; mark seen
    if (r,c) == (n-1, n-1): return cost
    for each in-bounds unseen neighbor (nr,nc):
        push(heap, (max(cost, grid[nr][nc]), nr, nc))

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

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