Swim in Rising Water
Problem
In an n x n grid, grid[i][j] is the elevation of each cell. At time t the water level is t, and you can move between adjacent cells only if both have elevation at most t. Return the earliest time you can travel from the top-left cell to the bottom-right cell.
Examples
Constraints
- • 1 <= n <= 50
- • 0 <= grid[i][j] < n^2
- • All elevations are distinct
Hints & approach
Hint 1
The cost of a path is the maximum elevation along it, not the sum.
Hint 2
Minimize that maximum: a Dijkstra-style search where path cost is max(current, next cell).
Hint 3
Binary search on t with a reachability check also works.
Approachtry the hints first
Run a modified Dijkstra with a min-heap of (time, row, col), starting from (grid[0][0], 0, 0). Pop the cell with the smallest required time; if it is the destination, return that time. Otherwise push each unvisited neighbour with max(time, neighbour elevation). Because the path cost is monotone non-decreasing, the first time the destination is popped is optimal.
Time O(n^2 log n) · Space O(n^2)