Cheapest Flights Within K Stops
Explanation & Solution
Description
You are given n cities connected by some number of flights. You are given an array flights where flights[i] = [from, to, price] represents a flight from city from to city to with cost price.
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 any intermediate city between src and dst — the source and destination themselves do not count as stops.
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
Explanation: The cheapest path with at most 1 stop is 0 → 1 → 3 with cost 100 + 600 = 700. The path 0 → 1 → 2 → 3 costs 400 but uses 2 stops, which exceeds k = 1.
Constraints
1 <= n <= 1000 <= flights.length <= n * (n - 1) / 2flights[i].length == 30 <= from, to < nfrom != to1 <= price <= 100000 <= src, dst, k < nsrc != dst
Approach
Graphs pattern
1. Initialize Distance Array
- Create a
pricesarray of sizen, filled withInfinity - Set
prices[src] = 0since the cost to reach the source is zero
2. Iterate k + 1 Times (Bellman-Ford Relaxation)
- We allow at most k stops, which means at most k + 1 edges
- For each iteration:
- Create a copy
tempof the currentpricesarray - This copy is critical — it prevents using a path updated in the same iteration, which would allow more edges than intended
3. Relax All Edges
- For each flight
[from, to, price]: - If
prices[from]isInfinity, skip — we cannot reachfromyet - If
prices[from] + price < temp[to], updatetemp[to] - We read from
prices(previous iteration) and write totemp(current iteration)
4. Update Prices
- After processing all edges, set
prices = temp - This ensures each iteration only extends paths by one edge
5. Return the Result
- If
prices[dst]is stillInfinity, no valid route exists — return-1 - Otherwise, return
prices[dst]as the cheapest price
Key Insight
- Standard Bellman-Ford relaxes edges
n - 1times to find shortest paths. Here, we only relax k + 1 times because we are limited to at most k stops (k + 1 edges). The critical detail is copying thepricesarray before each iteration — without this, a single iteration could chain multiple edges together, violating the stop constraint. This modified Bellman-Ford runs in **O((k + 1) * E)** time where E is the number of flights.
Visualization
Press play to start bellman-ford