Cheapest Flights Within K Stops
Master this topic with zero to advance depth.
Cheapest Flights Within K Stops
There are n cities connected by some number of flights. You are given an array flights where flights[i] = [from_i, to_i, price_i] indicates that there is a flight from city from_i to city to_i with cost price_i.
You are also given three integers src, dst, and k. Return the cheapest price from src to dst with at most k stops. If there is no such route, return -1.
Visual Representation
(0) --100--> (1) --100--> (2)
| ^
|----------500------------|
K = 1:
Path 0 -> 1 -> 2: Price 200. Stops: 1 (OK)
Result: 200
K = 0:
Path 0 -> 2: Price 500. Stops: 0 (OK)
Path 0 -> 1 -> 2: Stops: 1 (FAIL)
Result: 500Examples
0 to 1 then to 2 is cheapest within 1 stop.
Level I: Brute Force (BFS with Depth)
Intuition
We can use BFS to explore paths level by level. Each level represents one 'stop'. We stop exploring when we exceed stops.
Thought Process
- Build adjacency list.
- Queue stores
(node, current_price, current_stops). - Keep a
min_pricesarray to prune paths that are more expensive than what we've seen at a certain node. - While queue is not empty:
- Pop
(u, price, stops). - If
stops > k, skip. - For each neighbor
vwith flight costw:- If
price + w < min_prices[v]:min_prices[v] = price + w.- Push
(v, price + w, stops + 1).
- If
- Pop
Pattern: Level-wise BFS
Detailed Dry Run
k=1, src=0, dst=2, edges=[[0,1,100],[1,2,100],[0,2,500]]
- Queue: [(0, 0, -1)] (stops starts at -1 as first flight is 0 stops)
- Pop (0,0,-1). Neighbors: (1, 100, 0), (2, 500, 0). min_prices: {1:100, 2:500}
- Pop (1,100,0). Neighbors: (2, 200, 1). 200 < 500. min_prices: {2:200}
- Pop (2,500,0). Neighbors: None.
- Pop (2,200,1). Stops = k. Done. Result: 200
Level III: Optimal (Bellman-Ford / BFS)
Intuition
Dijkstra focuses on shortest distance, but here we have a constraint on the number of edges (stops). Bellman-Ford is perfect for this: we run the relaxation process exactly k+1 times to find the shortest path with at most k edges.
Thought Process
- Initialize
pricesarray with infinity,prices[src] = 0. - For
ifrom 0 tok:- Create a
tempcopy ofpricesto avoid using updated prices from the SAME iteration (level-wise relaxation). - For each flight
(u, v, cost):- If
prices[u]is not infinity, updatetemp[v] = min(temp[v], prices[u] + cost).
- If
- Set
prices = temp.
- Create a
- Return
prices[dst]if reachable, else-1.
Pattern: Constrained Shortest Path
Detailed Dry Run
k=1, src=0, dst=2, flights=[[0,1,100],[1,2,100],[0,2,500]]
| Iter | 0 | 1 | 2 | Actions |
|---|---|---|---|---|
| Init | 0 | inf | inf | - |
| 1 | 0 | 100 | 500 | Relax edges from 0 |
| 2 | 0 | 100 | 200 | Relax edge 1->2 (100+100=200) |
| Result: 200 |
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.