Minimum Travel Cost with Layover Limit
Trees & GraphsAuto-graded · 24 test casesLast updated
Tests weighted shortest-path reasoning under a hard constraint on the number of edges traversed, requiring a round-bounded relaxation strategy.
Problem Statement
You are planning a trip across a network of cities connected by one-way routes. Each route has a fixed fare. Given the network, a starting city, a destination city, and a maximum number of layovers allowed, find the lowest total fare for any valid itinerary.
You are given:
num_cities— the total number of cities, labeled0throughnum_cities - 1.routes— a list of connections, where eachroutes[i] = [origin, destination, fare]describes a direct one-way flight with the given fare.start— the city you depart from.end— the city you need to reach.max_layovers— the maximum number of intermediate stops (layovers) permitted.
Return the minimum total fare to travel from start to end using at most max_layovers intermediate stops. If no valid itinerary exists, return -1.
A trip with max_layovers = 1 may use at most two flights: one from start to some intermediate city, and one onward to end. A direct flight uses zero layovers.
If start equals end, the cost is 0 regardless of the routes available.
Constraints
1 <= num_cities <= 1000 <= len(routes) <= num_cities * (num_cities - 1) / 20 <= origin, destination, start, end < num_cities0 <= fare <= 10,0000 <= max_layovers < num_cities- There are no negative fares.
Examples
Example 1
Input: min_travel_cost(4, [[0, 1, 100], [1, 2, 100], [2, 3, 200], [1, 3, 600]], 0, 3, 1)
Output: 700
Example 2
Input: min_travel_cost(3, [[0, 1, 100], [1, 2, 100], [0, 2, 500]], 0, 2, 1)
Output: 200
Example 3
Input: min_travel_cost(3, [[0, 1, 100], [1, 2, 100]], 0, 2, 0)
Output: -1
Example 4
Input: min_travel_cost(4, [[0, 1, 100], [1, 2, 100]], 0, 0, 0)
Output: 0
Hints
Hint 1
An itinerary with at most k layovers uses at most k + 1 individual flights — think in terms of the number of edges (flights) rather than the number of nodes (cities).
Hint 2
Consider processing all routes in rounds, where round i computes the cheapest way to reach each city using exactly i flights. Crucially, within a single round you should only use costs from the previous round, not ones updated during the current round — otherwise a single round could silently chain multiple flights.
Hint 3
If you snapshot the cost array at the start of each round and write updates into the copy, you prevent that chaining problem and stay within the edge budget. Run exactly k + 1 such rounds.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Reframing the Constraint
"At most max_layovers intermediate stops" is equivalent to "at most max_layovers + 1 individual flights." The problem is therefore a shortest-path problem where the path length (measured in edges) is bounded. That edge-count bound is the key structural property to exploit.
Why Dijkstra Does Not Directly Apply
Standard Dijkstra greedily settles each node at its globally cheapest cost and never revisits it. Here, a cheap path that uses too many flights might reach a city first and permanently block a more expensive path that uses fewer flights. That pricier path could be the only one that keeps the trip within the layover budget. Any correct approach needs to track cost per flight count used, not just minimum cost overall.
Bounded Bellman-Ford
Bellman-Ford has a useful invariant: after round i, the cost array holds the cheapest fare reachable using at most i edges. Running exactly max_layovers + 1 rounds therefore yields the answer directly.
There is one critical implementation detail. Within a single round, every relaxation must read from the cost array as it stood at the start of that round, not from values already updated during the same round. If you skip this, a single round can chain multiple flights together (updating city A, then immediately using the updated A to improve city B), silently consuming more edges than the round budget allows. The fix is to take a snapshot of the cost array before each round and write all updates into the copy.
Algorithm
- Initialize
costs = [inf] * num_citiesand setcosts[start] = 0. - Repeat
max_layovers + 1times:- Copy
costsintonext_costs. - For every route
(origin, destination, fare): iforiginwas reachable last round, try to improvenext_costs[destination]withcosts[origin] + fare. - Replace
costswithnext_costs.
- Copy
- Return
costs[end], or-1if it is still infinity.
Correctness
By induction on round number i:
- Base: before any round,
costs[start] = 0(zero flights used) and all other cities are unreachable — correct. - Step: assume
costscorrectly represents cheapest fares with at mostiflights. Any optimal path to a cityvusing at mosti + 1flights either usesior fewer flights (preserved becausenext_costsstarts as a copy) or extends the besti-flight path to some cityuby the edgeu → v(captured by the relaxation loop). Because we only read from the snapshot, no path longer thani + 1flights can sneak in.
After max_layovers + 1 rounds, costs[end] holds the exact answer. Fares are non-negative so there are no negative cycles to worry about.
Edge Cases
start == end:costs[start]is initialized to 0 and non-negative fares can never decrease it, so the answer is correctly 0.- No routes, or
endunreachable within the flight budget:costs[end]remains infinity, so the function returns -1. max_layovers = 0: exactly one round runs, so only direct flights are considered.- Zero-price routes: handled naturally; the snapshot copy prevents free routes from chaining within one round.
Complexity
- Time: O((max_layovers + 1) × E), where E =
len(routes). With E at most n² and n ≤ 100, this is at most around 10⁶ operations. - Space: O(n) for the two cost arrays. The edge list is iterated directly with no adjacency structure needed.
Reference Solution
from typing import List
def min_travel_cost(num_cities: int, routes: List[List[int]], start: int, end: int, max_layovers: int) -> int:
max_flights = max_layovers + 1 # k layovers == at most k + 1 flights
inf = float('inf')
# costs[i] = cheapest fare to reach city i within the current flight budget
costs = [inf] * num_cities
costs[start] = 0
for _ in range(max_flights):
# Snapshot: all relaxations in this round read from the previous round's values
next_costs = costs[:]
for origin, destination, fare in routes:
if costs[origin] != inf:
candidate = costs[origin] + fare
if candidate < next_costs[destination]:
next_costs[destination] = candidate
costs = next_costs
return -1 if costs[end] == inf else costs[end]