Cheapest Flights Within K Stops
The key idea
Bellman-Ford fits perfectly: relax all edges exactly k+1 times (k stops means at most k+1 flights). Snapshot the distances before each round so a single round can only extend a path by one more flight, never chain several relaxations within the same round.
Problem
There are n cities connected by some number of flights. You are given an array flights where each 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.
A "stop" is an intermediate city on the path, so a route with at most k stops uses at most k + 1 flights.
Constraints
1 <= n <= 1000 <= flights.length <= (n * (n - 1) / 2)flights[i].length == 30 <= from_i, to_i < nfrom_i != to_i1 <= price_i <= 10^4- There will not be any multiple flights between two cities.
0 <= src, dst, k < nsrc != dst
Examples
Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1
Output: 200
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
Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0
Output: 500
Complexity
Time: O(k * E) Space: O(n)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Graph problems
- Clone GraphMEDIUM
- Course Schedule IVMEDIUM
- Evaluate DivisionMEDIUM
- Find the Town JudgeEASY
- Min Cost to Connect All PointsMEDIUM
- Minimum Height TreesMEDIUM
- Network Delay TimeMEDIUM
- Number of ProvincesMEDIUM
- Path With Minimum EffortMEDIUM
- Reconstruct ItineraryHARD
- Swim in Rising WaterHARD