Minimum Cost Route with Limited Layovers
Trees & GraphsAuto-graded · 21 test casesLast updated
Tests understanding of constrained shortest-path algorithms on directed weighted graphs with edge-count restrictions.
You have a network of cities connected by direct flights. Each flight has a fixed price. Your task is to find the lowest-cost route between two cities, subject to a limit on how many intermediate cities you can pass through.
Write a function that takes:
n: the total count of cities, numbered from0ton-1flights: a list where each entry is[origin, destination, cost], representing a one-way flightsource: the city where your journey beginstarget: the city where your journey endsmax_layovers: the maximum number of intermediate cities allowed on your route
A layover is a city you pass through between source and target. For example, the route A → B → C → D has two layovers (cities B and C), meaning it uses three flights.
Return the minimum total cost of any valid route from source to target. If no valid route exists, return -1.
Constraints
1 ≤ n ≤ 1000 ≤ flights.length ≤ n * (n - 1)flights[i].length == 30 ≤ origin, destination < norigin ≠ destination0 ≤ cost ≤ 10⁴0 ≤ source, target < n0 ≤ max_layovers < n- All flight costs are non-negative
Examples
Example 1
Input: min_cost_route(4, [[0, 1, 100], [1, 2, 100], [2, 3, 100], [0, 3, 500]], 0, 3, 1)
Output: 500
Hints
Hint 1
Think about how many flights you can take if you're allowed max_layovers intermediate stops.
Hint 2
A modified Bellman-Ford that runs for a limited number of iterations naturally enforces an edge-count constraint.
Hint 3
Make sure to snapshot the cost array before each relaxation round to avoid accidentally counting paths with more edges than intended.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem asks for the shortest path with a constraint on the number of edges used. If we allow k layovers, we can take at most k + 1 flights (edges). The key insight is to use a bounded version of the Bellman-Ford algorithm.
Standard Bellman-Ford relaxes all edges repeatedly. After i iterations, it has computed the shortest paths using at most i edges. We adapt this by running exactly max_layovers + 1 iterations.
Critical detail: Each iteration must use only the costs computed in the previous iteration. We create a snapshot of the cost array before processing edges. This prevents a single iteration from discovering paths longer than intended. Without the snapshot, relaxing edge A→B would update cost[B], and then immediately relaxing B→C would use that fresh value, effectively finding a two-edge path in a single iteration.
The algorithm maintains an invariant: after iteration i, costs[v] represents the minimum cost to reach city v from source using at most i edges.
Base case: Initially, only source is reachable with zero edges, at cost 0. All other cities have cost infinity.
Inductive step: For iteration i, the best path to any city using at most i edges either:
- Uses fewer than
iedges (already captured in the previouscostsarray), or - Uses exactly
iedges, ending with some flightu → v. The cost isprevious_costs[u] + flight_cost, which we capture by relaxing all edges.
After max_layovers + 1 iterations, costs[target] holds the answer. If it remains infinity, no valid route exists.
Why not Dijkstra? Standard Dijkstra settles each node at its globally cheapest cost and never revisits it. A cheap multi-hop path can settle a node before a pricier but shorter path arrives, blocking the shorter path even if it's the only one satisfying the hop constraint. You can modify Dijkstra by tracking (city, hops_used) as state, but the bounded Bellman-Ford approach is simpler and more straightforward.
Complexity
Time: O((max_layovers + 1) · E) where E is the number of flights. We perform max_layovers + 1 iterations, each scanning all edges once. The array copy adds O(n) per iteration.
Space: O(n) for the two cost arrays.
Solution
from typing import List
def min_cost_route(n: int, flights: List[List[int]], source: int, target: int, max_layovers: int) -> int:
inf = float('inf')
costs = [inf] * n
costs[source] = 0
for _ in range(max_layovers + 1):
next_costs = costs[:]
for origin, destination, price in flights:
if costs[origin] != inf:
next_costs[destination] = min(next_costs[destination], costs[origin] + price)
costs = next_costs
return -1 if costs[target] == inf else costs[target]