Cheapest Flights Within K Stops
1 approach, code in every language
Problem description
There are `n` cities connected by some flights. Each flight is given as `flights[i] = [from, to, price]`, meaning there is a one-directional flight from city `from` to city `to` costing `price`.
Given a starting city `src`, a target city `dst`, and an integer `k`, return the cheapest total price to travel from `src` to `dst` using at most `k` stops. A "stop" is an intermediate city, so a route with `k` stops uses up to `k + 1` flights.
If no route satisfies the stop limit, return `-1`.
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
With at most 1 stop, the route 0 -> 1 -> 3 costs 700. The cheaper 0 -> 1 -> 2 -> 3 (400) uses 2 stops and is not allowed.
Example 2
Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0
Output: 500
No stops are allowed, so only the direct flight 0 -> 2 for 500 qualifies; 0 -> 1 -> 2 would require one stop.
Constraints
1 <= n <= 1000 <= flights.length <= n * (n - 1) / 2flights[i].length == 30 <= from_i, to_i < nfrom_i != to_i1 <= price_i <= 10^4There is at most one flight between any ordered pair of cities.0 <= src, dst, k < nsrc != dst
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Limited Handoff Courier Route is our own problem on the technique behind Cheapest Flights Within K Stops: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free