Example 1
- Input
- n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1
- Output
- 700
Trip 0 to 1 to 3 costs 700 with one stop, while the cheaper 400 route needs two stops and breaks the limit.
Each flight links two cities with a price, and k caps how many intermediate stops a trip may use. Return the cheapest fare from the start city to the destination within that limit, or -1 when no such trip exists.
There are n cities linked by flights, where flights[i] = [from, to, price] is a directed flight costing price. Given a start city src, a destination city dst, and an integer k, return the cheapest price of any trip from src to dst using at most k stops.
A stop is an intermediate city, so k stops means at most k + 1 flights. If no trip respects the limit, return -1.
2 <= n <= 1000 <= flights.length <= (n * (n - 1) / 2)flights[i].length == 30 <= from, to < nfrom != to1 <= price <= 10^4(from, to) pair.0 <= src, dst, k < nsrc != dstTrip 0 to 1 to 3 costs 700 with one stop, while the cheaper 400 route needs two stops and breaks the limit.
Trip 0 to 1 to 2 costs 200 with one stop, beating the direct 500 flight.
With zero stops allowed, only the direct 0 to 2 flight qualifies.
The cheapest arrival at a city is not enough information: it may have spent too many flights to continue. In Example 1, 0 to 1 to 2 to 3 costs only 400 but uses three flights, while the two-flight budget permits 0 to 1 to 3 for 700. Enumerate budget-limited walks, or share their work by remembering the cheapest arrival at each city after each allowed flight count. A relaxation round extends only the previous round, so it cannot accidentally spend extra flights.
Reveal DFS Every Route: intuition, complexity, and code
k + 1 flights fit the budget, which matches one extra flight of reach per relaxation round.-1.k = 0, where only a direct flight qualifies and a single round decides the answer.k times instead of k + 1, which prices trips with one flight too few.When a shortest path also caps the edge count, limit the relaxation rounds to the cap instead of running the textbook algorithm to convergence.