Parcel With Few Handoffs

Hardshortest pathAlso known as Cheapest Flights Within K Stops

You ship a fragile vase from your pottery shop through a network of courier depots. Each route between two depots is one-way, run by a different firm, and has its own fee. Chaining cheap routes is usually the best deal.

But every stop at a depot in between means unloading and reloading, and that is when vases break. So you allow at most maxStops stops between the drop-off depot and the buyer's depot. What is the cheapest way to send it?

Your task

Write cheapestDelivery(n, routes, origin, dest, maxStops). Depots are numbered 0 to n - 1. Each [a, b, fee] in routes is a one-way route from depot a to depot b. Return the lowest total fee to get from origin to dest passing through at most maxStops depots in between.

A direct route has 0 stops. A trip using 3 routes has 2 stops. Return -1 if no trip within the limit exists.

cheapestDelivery(n: int, routes: int[][], origin: int, dest: int, maxStops: int) → int

Examples

Example 1
Input
n = 4
routes = [[0, 1, 10], [1, 2, 10], [2, 3, 10], [0, 3, 50], [0, 2, 25]]
origin = 0
dest = 3
maxStops = 1
Output
35
Why

The cheapest trip, 0 → 1 → 2 → 3 for 30, stops twice. With at most 1 stop, the choices are 0 → 3 for 50 and 0 → 2 → 3 for 35.

Example 2
Input
n = 3
routes = [[0, 1, 5], [1, 2, 5]]
origin = 0
dest = 2
maxStops = 0
Output
-1
Why

The only trip stops at depot 1, and no stops are allowed.

Constraints

  • 2 ≤ n ≤ 100
  • 0 ≤ routes.length ≤ 2,000
  • 0 ≤ a, b < n and a ≠ b; no route is listed twice
  • 1 ≤ fee ≤ 10,000
  • origin ≠ dest
  • 0 ≤ maxStops < n
Start with brute force

Try every trip of up to maxStops + 1 routes with a depth-first search and keep the cheapest that ends at dest. The number of trips grows like (routes per depot)stops, so a dense network with 99 allowed stops is far out of reach.

Plain Dijkstra is fast but wrong here. It keeps only the cheapest fee per depot and discards a pricier path with fewer stops, which may be the only one still allowed to reach dest.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code