There are n cities (0 .. n-1) connected by flights[i] = [from, to, price] (directed). Given src, dst, and k, return the cheapest price from src to dst using at most k stops (so at most k+1 flights), or -1 if there is no such route.
Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1 Output: 200 0→1→2 costs 200 with one stop, cheaper than the direct 500.
Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0 Output: 500 With no stops, only the direct flight is allowed.
- 1 <= n <= 100 - 0 <= flights.length <= n*(n-1) - 0 <= src, dst < n - 0 <= k < n - 1 <= price <= 10^4
The twist over plain shortest path is the stop limit: you can't just take the globally cheapest route if it uses too many flights. The clean handle is to bound the number of edges, not just minimise cost.
Bounded Bellman-Ford. A path with at most k stops has at most k+1 edges, and Bellman-Ford's i-th round settles all shortest paths using at most i edges. So run exactly k+1 rounds — but relax each round using the previous round's distances (a fresh copy), so a single round can't chain multiple edges. O(k·E).
Level BFS. Equivalently, BFS level by level from src, where each level adds one flight; stop after k+1 levels. Track the best cost to each city and only enqueue improvements. Same O(k·E) bound.
“k stops or k flights?”
k stops = k+1 flights.
“No valid route?”
Return -1.
At most k stops means at most k+1 edges, so I run Bellman-Ford for exactly k+1 rounds.
I relax each round off the previous round's distances so one round adds only one flight.
Worked example — n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src=0, dst=2, k=1
1 stop allowed: 0->1->2 = 200 (2 flights) beats the direct 0->2 = 500 answer = 200
Bound the edge count, not just the cost.
So k+1 rounds suffice.
Copy distances each round to add one edge at a time.
| Bounded Bellman-Ford | Level BFS | |
|---|---|---|
| Idea | k+1 rounds, relax off a copy | expand one flight per level, k+1 levels |
| Time | O(k·E) | O(k·E) |
| Edge bound | rounds | levels |
Both respect the stop limit and give the same cheapest price. Full code is in the Approaches selector below.
Key takeaway
At most k stops = at most k+1 flights. Run Bellman-Ford for k+1 rounds, relaxing each round off the previous round's distances; or BFS level by level, k+1 levels. O(k·E).
for round in 0..k: tmp = copy(dist); relax all edges into tmp; dist = tmp answer = dist[dst] or -1