Maps app~30 min2s · 256 MBtarget O((n + m) log n) time, O(n + m) spaceclassic twin: lc-1631dijkstra
A hiking app plans a route between trail junctions. Each junction has an elevation in metres, and each trail joins two junctions and can be walked both ways.
Walking uphill tires the knees. The rise of one step is the elevation of the junction ahead minus the junction behind, and a step downhill rises nothing. A hiker does not mind a long walk, but wants to avoid any steep step. The app shows the route whose steepest single rise is as small as possible.
Write smallest_worst_climb(height, trails, start, finish).
height[i] is the elevation of junction i. The number of junctions is len(height).trails[i] = [a, b] is a trail between two different junctions, walkable both ways. A pair may be listed more than once.start to finish. Its worst climb is the largest rise of any step, where a step from x to y rises max(0, height[y] - height[x]).0 when start equals finish, and -1 when no route exists.Input: height = [10, 40, 25, 60, 30, 35], trails = [[0, 1], [0, 2], [1, 3], [2, 4], [4, 5], [3, 5]], start = 0, finish = 5
Output: 15The solution is Dijkstra's algorithm with a different rule. The cost of a route is its worst climb, so it is the larger of the route so far and the next step, and not their sum. The junction with the smallest worst climb is taken first.
| Junction taken | Elevation | Worst climb on its best route |
|---|---|---|
| 0 | 10 | 0 |
| 2 | 25 | 15 |
| 4 | 30 | 15 |
| 5 | 35 | 15 |
The route 0, 2, 4, 5 climbs 15, 5 and 5, so its worst climb is 15. The route over the peak at junction 3 has a climb of 30.
Input: height = [5, 3, 1], trails = [[0, 1], [1, 2]], start = 0, finish = 2
Output: 0Every step goes downhill, so nothing is climbed.
Input: height = [1, 2, 3, 4], trails = [[0, 1], [2, 3]], start = 0, finish = 3
Output: -1No trail joins junctions 0 and 1 to junctions 2 and 3.
1 ≤ len(height) ≤ 10,000, and 0 ≤ height[i] ≤ 1,000,0000 ≤ len(trails) ≤ 20,000, and each trail joins two junctions numbered below len(height)0 ≤ start, finish < len(height)There can be about 20,000 distinct rises, and trying each one with a full search would take about 400,000,000 steps. A route can also be very long, so trying all routes is impossible. An algorithm that handles each trail a few times, with a heap, takes about 280,000 steps.