Water rises one unit a minute; when can you swim from corner to corner? Dijkstra with a min-heap keyed on the tallest cell along the path.
▼The problem
LeetCode 778 (Hard). An n × n grid holds the elevations 0..n²-1 (all different). At time t the water is t deep everywhere, and you can swim between 4-adjacent cells when both elevations are at most t. Return the least time to get from the top left (0, 0) to the bottom right (n-1, n-1).
Examples (LeetCode's): [[0,2],[1,3]] → 3 (the corner itself is 3 high), and the 5 × 5 spiral [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]] → 16.
The solution
from heapq import heappush, heappop
def swim_in_water(grid):
n = len(grid)
heap, seen = [(grid[0][0], 0, 0)], {(0, 0)}
while heap:
t, r, c = heappop(heap)
if r == c == n - 1:
return t
for nr, nc in (r+1, c), (r-1, c), (r, c+1), (r, c-1):
if 0 <= nr < n and 0 <= nc < n and (nr, nc) not in seen:
seen.add((nr, nc))
heappush(heap, (max(t, grid[nr][nc]), nr, nc))Transcript
Swim in Rising Water. In an n by n grid of heights, at time t the water is t deep, and you can swim between neighbors that are both at most t. Find the least time from top left to bottom right.
For zero, two, one, three, the corner is three high: answer three. In the five by five spiral, the path stays blocked until the water hits sixteen.
The direct way: for each time t, flood fill and check the corner. Here, seventeen fills. That's n squared fills of n squared cells: n to the fourth.
The key idea: a path costs its highest cell, not the sum. The top route adds up to less, but climbs to eight. The left one stays at six. So run Dijkstra with a min heap keyed by the highest cell so far. When the corner pops, its key is the answer. It's Network Delay Time, with max instead of plus.
In code, the heap starts at the top left. Pop the smallest key. At the corner, return it. Otherwise, push each new neighbor with the larger of the key and its height.
On the spiral, zero to five pop in order. Then the lowest edge cell is sixteen; the twenties wait. Past sixteen, every cell is lower, so the key stays sixteen to the corner.
Each cell is pushed once: n squared log n time, n squared space. Binary search on time, or union find by height, also works.
Lowest cell first, keep the highest, stop at the corner. That's Swim in Rising Water.