Parcel With Few Handoffs
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
n = 4 routes = [[0, 1, 10], [1, 2, 10], [2, 3, 10], [0, 3, 50], [0, 2, 25]] origin = 0 dest = 3 maxStops = 1
35
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.
n = 3 routes = [[0, 1, 5], [1, 2, 5]] origin = 0 dest = 2 maxStops = 0
-1
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- Hint 1
In the first example, what is the cheapest fee to each depot using exactly 1 route? Using at most 2 routes? How does the second list follow from the first?
- Hint 2
"At most k stops" means "at most k + 1 routes". Think in rounds: after round r, you know the cheapest fee to every depot using at most r routes.
- Hint 3
To get round r + 1, extend every round-r trip by one route. The trap: if you update fees in place while going through the routes, one round can chain several routes. How do you prevent that?
- Hint 4
Run Bellman-Ford for exactly
maxStops + 1rounds. Each round, copy the fee array, then for every route[a, b, fee]updatecopy[b]using the old value ofa. Replace the array with the copy at the end of the round. The answer is the fee atdest, or -1 if it is still infinite.
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.
How to solve it
At most maxStops stops means at most maxStops + 1 routes, and Bellman-Ford counts routes. Each round extends every known trip by one route, so after round r the array holds the cheapest fee using at most r routes. Stop after maxStops + 1 rounds.
Trace the first example with maxStops = 1, so 2 rounds. Fees start as [0, ∞, ∞, ∞].
- Round 1, reading [0, ∞, ∞, ∞]. From depot 0: depot 1 = 10, depot 3 = 50, depot 2 = 25. Routes out of 1 and 2 are skipped because their old fees are ∞. Result [0, 10, 25, 50].
- Round 2, reading [0, 10, 25, 50]. 1 → 2 gives 20, better than 25. 2 → 3 gives 25 + 10 = 35, better than 50. Result [0, 10, 20, 35].
The answer is 35. Round 2 used depot 2's old fee, 25, not the fresh 20. The 20 comes from 0 → 1 → 2, already 2 routes, so adding 2 → 3 would make 3. Reading from the old array is what enforces the limit.
Update in place instead, and when routes are listed in path order, one round can run along a whole chain. The test with routes 0→1→2→3 and no stops allowed catches it: in place, you would return 3 instead of 100.
function cheapestDelivery(n, routes, origin, dest, maxStops) {
let best = new Array(n).fill(Infinity);
best[origin] = 0;
// round r: cheapest fee using at most r routes
for (let round = 1; round <= maxStops + 1; round++) {
const next = best.slice(); // read from best, write to next
for (const [a, b, fee] of routes) {
if (best[a] === Infinity) continue;
if (best[a] + fee < next[b]) next[b] = best[a] + fee;
}
best = next;
}
return best[dest] === Infinity ? -1 : best[dest];
}def cheapest_delivery(n, routes, origin, dest, max_stops):
INF = float('inf')
best = [INF] * n
best[origin] = 0
# round r: cheapest fee using at most r routes
for _ in range(max_stops + 1):
nxt = best[:] # read from best, write to nxt
for a, b, fee in routes:
if best[a] != INF and best[a] + fee < nxt[b]:
nxt[b] = best[a] + fee
best = nxt
return -1 if best[dest] == INF else best[dest]Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.