0:00 / 0:00

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.

TRY IT ON LEETCODE ▶

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. You get an n by n grid of heights, all different. At time t, the water is t deep, and you can swim between two neighbors only when both are at most t. Find the least time to get from the top left to the bottom right.

Take zero, two, one, three. The corner itself is three high, so the answer is three. In this five by five spiral, the way stays blocked until the water reaches sixteen.

The direct way: try each time in turn. Flood fill from the start through every cell at most t, and check the corner. Here that's seventeen fills. In general, n squared fills of n squared cells: n to the fourth.

The key idea: a route costs its highest cell, not the sum. The top route adds up to less, but it climbs to eight. The left route never goes above six, so it wins.

So run Dijkstra with a min heap, keyed by the highest cell so far. Always swim to the lowest cell on the shore. When the corner comes off the heap, its key is the answer. It's Network Delay Time, with max instead of plus.

In code, the heap starts with 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 through five pop in order. Now the lowest cell on the shore is sixteen; the twenties wait. Sixteen pops, and the key jumps to sixteen. Past it, every cell is lower, so the key stays sixteen to the corner.

Each cell is pushed once, and each heap step costs log n: n squared log n time, n squared space. Binary search on the time, or union find by height, also works.

Lowest cell first, keep the highest, stop at the corner. That's Swim in Rising Water.