Swim in Rising Water
Find the earliest water level at which a path exists from the top-left to bottom-right cell.
Open on LeetCode ↗Intuition
Enumerating paths is exponential, while binary-searching time repeats a reachability traversal. A path's cost is not the sum of its cells; it is the maximum elevation encountered. Dijkstra's algorithm still applies when relaxation combines costs with max instead of addition. The first time the destination leaves the min-heap, its smallest possible bottleneck is finalized.
A path objective that minimizes the maximum edge or vertex value is a bottleneck shortest-path problem. Dijkstra works by replacing additive relaxation with the operation that defines the path cost, here max.
Approach
Treat elevation as a bottleneck path cost
Start with cost grid[0][0]. Moving onto a neighbor changes the route cost to the larger of the current cost and the neighbor's elevation.
Expand the lowest known bottleneck first
Keep (cost, row, col) states in a min-heap and ignore stale entries. This ordering ensures no later route can improve a cell after its best cost is popped.
Stop when the destination is finalized
Relax four-directional neighbors whenever the candidate bottleneck is smaller than their stored value. Return immediately when the bottom-right cell is popped, because that value is globally minimal.
Solution
Common pitfalls
Adding elevations
candidate = cost + grid[nr][nc]
candidate = max(cost, grid[nr][nc])
Waiting time is determined by the highest cell, not the sum of elevations.
Returning when the destination is pushed
if (nr, nc) == target:
return candidateif (row, col) == target:
return costA pushed destination may later receive a smaller bottleneck route.
Marking every discovered cell permanently
visited.add((nr, nc))
if candidate < best[nr][nc]:
best[nr][nc] = candidateA cell can be discovered first through a worse bottleneck.
Edge cases
The start is also the destination, so return its elevation.
Heap ordering can prefer a longer route with a lower maximum elevation.
Every route cost begins at that elevation and never decreases.