SDE & MLE Prep

778. Swim in Rising Water

Problem

grid[i][j] is the elevation of a cell in an n×n grid (all values distinct, 0…n² − 1). At time t the water everywhere is t deep, and you can swim between adjacent cells (up, down, left, right) instantly if both elevations are at most t. Starting at the top-left, return the least time at which you can reach the bottom-right.

Example: [[0,2],[1,3]] → 3

Constraints: n ≤ 50.

Cost of a path = the max cell on it. Dijkstra where the "distance" is max(current, grid[next]): always expand the lowest-elevation frontier cell.

Complexity: O(n² log n).

class Solution:
    def swimInWater(self, grid: List[List[int]]) -> int:
        n = len(grid)
        pq, seen = [(grid[0][0], 0, 0)], {(0, 0)}
        while pq:
            t, r, c = heappop(pq)
            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(pq, (max(t, grid[nr][nc]), nr, nc))