Ride-hailing app~25 min2s · 256 MBtarget O(rows x cols x log(rows x cols)) time, O(rows x cols) spaceclassic twin: lc-1631dijkstra · grid-bfs
A bike courier crosses a city drawn as a grid of blocks. Each block has a height above sea level. The courier starts at the top-left block and must reach the bottom-right block, moving one block at a time up, down, left or right.
Each move climbs or drops by the difference in height between the two blocks. The courier tires most on the steepest single move, not on the total. You want the ride whose steepest move is as gentle as possible.
Write gentlest_ride(heights).
heights is a rectangle of rows, each a list of block heights.heights[0][0] and ends at the last block of the last row. Each move goes to a neighbouring block.Input: heights = [[5,6,9,1],[8,4,1,3],[2,6,8,4]]
Output: 3The best ride passes the blocks with heights 5, 6, 4, 1, 3 and 4. Its steps are 1, 2, 3, 2 and 1, so its steepest step is 3.
The solution takes blocks from a heap in order of effort. A block's effort is the smallest steepest move on any ride to it. A move onward has the larger of the old effort and its own step.
| Row | Column 0 | Column 1 | Column 2 | Column 3 |
|---|---|---|---|---|
| 0 | 0 | 1 | 3 | 3 |
| 1 | 3 | 2 | 3 | 3 |
| 2 | 4 | 2 | 2 | 3 |
The last block has effort 3, so the answer is 3.
Input: heights = [[1,2],[2,3]]
Output: 1Every move between neighbouring blocks climbs by 1, so a ride across has effort 1.
Input: heights = [[4]]
Output: 0The start is the last block, so the ride has no move.
1 ≤ heights.length ≤ 200 and 1 ≤ heights[i].length ≤ 200, and every row has the same length1 ≤ heights[i][j] ≤ 1,000,000Trying every possible steepest-step limit can mean about 2 × 200 × 200 = 80,000 limits, and each needs a flood fill over 40,000 blocks, so about 3 × 10^9 steps. A heap-based search takes each block a few times at a cost of a logarithm, about 40,000 × 4 × 16 = 2.6 × 10^6 steps.