Cheapest Flights Within K Stops
Difficulty: Medium · Pattern: Graphs (BFS / DFS) · LeetCode #787
flights[i] = [from, to, price]. Find the cheapest price from src to dst using at most k stops (that is, at most k+1 flights). Return -1 if there's no such route.
Examples
text
n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1 → 700
(0→1→3; the cheaper 0→1→2→3 = 400 uses 2 stops)
n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1 → 200
n = 3, same flights, k = 0 → 500Hints
- Plain Dijkstra fails: the cheapest way to reach a middle node might use too many stops.
- Bellman-Ford's i-th round finds the best paths that use at most i edges. Run exactly k+1 rounds.
Approach
Bounded Bellman-Ford:
text
dist = [inf]*n; dist[src] = 0
repeat k+1 times:
nd = dist.copy() # ← crucial
for (u, v, p) in flights:
if dist[u] + p < nd[v]: nd[v] = dist[u] + p
dist = ndRelaxing from the previous round's array (dist) into a fresh copy (nd) ensures each round adds at most one edge. Updating in place could chain several flights in one round and break the stop limit. Total O((k+1)·E).
Dijkstra on (cost, node, stops) states also works if you allow revisiting a node with fewer stops.
Complexity
Time: O((k+1)·E). Space: O(n).
Python solution
def findCheapestPrice(n, flights, src, dst, k):
INF = float('inf')
dist = [INF] * n
dist[src] = 0
for _ in range(k + 1):
nd = dist[:]
for u, v, p in flights:
if dist[u] + p < nd[v]:
nd[v] = dist[u] + p
dist = nd
return -1 if dist[dst] == INF else dist[dst]JavaScript solution
function findCheapestPrice(n, flights, src, dst, k) {
let dist = new Array(n).fill(Infinity);
dist[src] = 0;
for (let i = 0; i <= k; i++) {
const nd = [...dist];
for (const [u, v, p] of flights) if (dist[u] + p < nd[v]) nd[v] = dist[u] + p;
dist = nd;
}
return dist[dst] === Infinity ? -1 : dist[dst];
}