Find the cheapest fare with at most k stops. Relax every flight once per allowed hop, Bellman-Ford style, keeping last round's prices.
▼The problem
LeetCode 787 (Medium). There are n cities and a list of flights [from, to, price]. Return the cheapest price from src to dst with at most k stops (at most k + 1 flights), or -1 if there is no such route.
Example (the one animated, LeetCode's example 1): 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).
from math import inf
def findCheapestPrice(n, flights, src, dst, k):
price = [inf] * n
price[src] = 0
for day in range(k + 1):
new = price[:] # copy
for a, b, fare in flights:
if price[a] + fare < new[b]:
new[b] = price[a] + fare
price = new
return -1 if price[dst] == inf else price[dst]TRY IT ON LEETCODE ▶The solution
from math import inf
def findCheapestPrice(n, flights, src, dst, k):
price = [inf] * n
price[src] = 0
for day in range(k + 1):
new = price[:] # copy
for a, b, fare in flights:
if price[a] + fare < new[b]:
new[b] = price[a] + fare
price = new
return -1 if price[dst] == inf else price[dst]Transcript
Cheapest Flights Within K Stops. You get n cities and flights, each with a price. Find the cheapest trip from a source to a destination with at most k stops, or return minus one.
Here are four cities. Flights go zero to one, one to two, and two to zero, for a hundred each. One to three costs six hundred, and two to three, two hundred. Fly from zero to three with at most one stop. Zero, one, two, three costs four hundred, but that's two stops. So take zero, one, three: seven hundred.
The simple way tries every route of up to k plus one flights. But routes branch at every city: exponential growth. And plain Dijkstra chases price alone: it finds four hundred, breaking the limit.
Instead, count flights: k stops means k plus one flights. So run Bellman-Ford for exactly k plus one rounds. Think of each round as a day: every flight takes off once, from yesterday's prices. After day d, each city holds its cheapest price using at most d flights.
In code, prices start at infinity; the source costs zero. Each day, copy the prices. For every flight, if yesterday's price at its start plus the fare beats the copy where it lands, lower it. Why copy? Updating in place lets one day chain two flights, sneaking in an extra stop.
Day one: only city zero has a price, so only flight zero to one flies. City one costs a hundred. Day two: from city one, city two gets two hundred, and city three gets seven hundred. Flight two to three can't fly, since yesterday city two had no price. Without the copy, it would chain to four hundred, with two stops. Answer: seven hundred.
Each day checks every flight once, so time is order k times E, the number of flights. Space is order n: the prices and their copy.
One flight per day, for k plus one days. That's Cheapest Flights Within K Stops.