Cheapest Flights Within K Stops
Find the cheapest fare between two cities when the trip may make at most k stops on the way.
The problem
There are n cities numbered 0 to n - 1, and each entry [from, to, price] in flights is a one-way flight. Find the cheapest trip from src to dst that makes at most k stops in between, which means at most k + 1 flights. Return its price, or -1 if no such trip exists.
Input n = 4, flights = [[0, 1, 2000], [1, 3, 2500], [0, 2, 1500], [2, 1, 300], [2, 3, 6000], [0, 3, 7000]], src = 0, dst = 3, k = 1
Output 4500
With one stop, 0 to 1 to 3 costs 2000 + 2500. The route 0, 2, 1, 3 is cheaper but needs two stops.
Input n = 4, flights = [[0, 1, 2000], [1, 3, 2500], [0, 2, 1500], [2, 1, 300], [2, 3, 6000], [0, 3, 7000]], src = 0, dst = 3, k = 2
Output 4300
Two stops are allowed now, so 0, 2, 1, 3 works: 1500 + 300 + 2500 = 4300.
Key constraint: The limit is on the number of flights, so the cheapest route overall may be one you are not allowed to take.
How to spot the pattern
- You want the cheapest route, with a cap on how many edges it may use.
- A route with more stops can be cheaper, so the cheapest way into a middle city may not be the one you need.
- The graph is small (at most 100 cities), so
k + 1passes over every flight are affordable.
The idea
Plain Dijkstra fails here: it settles each city at its cheapest price, but that cheapest way in may already use too many flights for the rest of the trip. So work in rounds instead, Bellman-Ford style. After round i, cost[c] is the cheapest price to reach city c with at most i flights; each round tries every flight once on top of the previous round's prices, so after k + 1 rounds cost[dst] is the answer.
Brute force: Try every route of at most k + 1 flights with DFS, which can take O(n^(k + 1)) time.
Step by step
- 1Set
cost[src] = 0and every other city to infinity. - 2Repeat
k + 1times, and start each round by copyingcostintonext, so the round only builds on last round's prices. - 3For every flight
[u, v, price]wherecost[u]is finite, setnext[v] = min(next[v], cost[u] + price). - 4Replace
costwithnextat the end of the round. - 5Return
cost[dst], or -1 if it is still infinity.
See the pattern move
The shortest paths pattern on a small example. Step through it, or press play.
Code
class Solution:
def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:
INF = float("inf")
# cost[c] = cheapest price to reach city c with the flights allowed so far
cost = [INF] * n
cost[src] = 0
for _ in range(k + 1): # k stops means at most k + 1 flights
next_cost = cost[:] # build only on last round's prices
for u, v, price in flights:
if cost[u] != INF and cost[u] + price < next_cost[v]:
next_cost[v] = cost[u] + price
cost = next_cost
return -1 if cost[dst] == INF else cost[dst]Complexity
Time
O((k + 1) * E)
Space
O(n)
There are k + 1 rounds and each one looks at all E flights once; only two price arrays of size n are kept.
Watch out for
- Updating
costin place during a round: a price set earlier in the same round gets extended again, so one round can add several flights. - Getting the limit off by one:
kstops meansk + 1flights, so runk + 1rounds. - Running Dijkstra with a visited set on cities alone: a city first reached cheaply but with too many stops blocks the route that would have worked.
Follow-up questions
Can Dijkstra still work here?
Yes, if the state is the pair (city, flights used) instead of just the city. Push (price, city, flights) and stop expanding a state once it has used k + 1 flights.
What if there were no limit on stops?
Then it is a plain shortest path with positive prices, and Dijkstra with a min-heap does it in O(E log E) time.
In Hinglish
Har round mein ek flight aur allow karo, par update sirf pichhle round ki prices se karo, isliye copy banao. k + 1 round ke baad `cost[dst]` hi jawab hai.