Parcel With Few Handoffs

Hardshortest pathAlso known as Cheapest Flights Within K Stops

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

But every time the parcel stops at a depot in between, it is unloaded and reloaded, and that is when vases break. So you allow at most maxStops stops between the depot where you drop it off and the depot where the buyer collects it. What is the cheapest way to send it under that rule?

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 overall is 0 → 1 → 2 → 3 for 30, but it stops twice. With at most 1 stop, the choices are 0 → 3 for 50 and 0 → 2 → 3 for 35. The answer is 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. Return -1.

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. With many routes out of each depot, 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 throws away a pricier path that used 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