Example 1
- Input
- grid = [[0,2],[1,3]]
- Output
- 3
At time 0 only the start is reachable. Both routes enter the destination of elevation 3, providing a lower bound of 3; the route through elevation 1 achieves that bound.
Given a square grid of elevations, find the smallest water level t at which a path from the top-left corner to the bottom-right corner exists using only cells whose elevation is at most t.
You are given an n x n integer matrix grid where grid[i][j] is the elevation of that cell. At time t the water depth everywhere equals t, so you may stand on or swim through a cell exactly when its elevation is at most t.
Starting at (0, 0) and moving in the four cardinal directions, return the smallest t for which the destination (n - 1, n - 1) is reachable. Every elevation is unique and lies below n * n, so the answer always exists.
n == grid.lengthn == grid[i].length1 <= n <= 500 <= grid[i][j] < n * ngrid is unique.At time 0 only the start is reachable. Both routes enter the destination of elevation 3, providing a lower bound of 3; the route through elevation 1 achieves that bound.
Follow the top row 0 through 4, descend through 5 and 16, cross left through 15, 14, 13 and 12, descend through 11 and 10, then cross the bottom row through 9, 8, 7 and 6. Its maximum is 16. Below 16 the start component ends at elevation 5, whose other exit is elevation 21; it cannot reach the bottom region.
The start is already the destination. No move is needed, and its elevation 0 is reachable immediately.
The low destination does not make time 1 sufficient: the starting cell itself needs time 3. At 3 the route down through 0 and right through 1 is usable.
A route is usable only after its highest cell is submerged. In Example 1, both routes must enter the destination of elevation 3, so even the route through elevation 1 needs time 3. A longer route can win if its highest cell is lower: the winding route in Example 2 avoids the ridge of elevations 17 through 24 and needs only 16. We can either test water levels in order, or guide the search by the highest elevation required to reach each cell.
Reveal Linear Scan Plus BFS: intuition, complexity, and code
t every cell up to elevation t is swimmable ground.t, it stays reachable at every higher level, which means levels can be scanned rather than paths enumerated.1 x 1 grid starts on the destination, so the answer is the single elevation with no moves.max(current cost, elevation) forgets the water already needed to get there.When a path cost is the worst edge along it rather than a sum, Dijkstra with a maximising cost function finds the minimax route in a single guided search.