Cheapest Flights Within K Stops
Find the cheapest trip between two cities when the number of stops on the way is limited.
There are nn - 1flights[from, to, price]fromtopricesrcdstksrcdstk
Example 1
Output: 700
Explanation: 0 → 1 → 3 costs 700 with one stop. 0 → 1 → 2 → 3 costs 400 but needs two stops.
Example 2
Output: 200
Explanation: 0 → 1 → 2 costs 200 with one stop, less than the direct flight for 500.
The Idea
When you book a trip, the cheapest ticket often has the most changes of plane, so many people set a limit such as "at most one stop". A stop is a city where you leave one plane and board the next. The cities where the trip starts and ends do not count.
Look at the picture below. It draws Example 1 twice. Each circle is a city, and each arrow is a flight with its price next to it. The arrow from 1 to 3 costs 600, and no arrow goes back from 3 to 1, because every flight goes one way. City 0, marked "start", is srcdst
On the left, the orange route 0 → 1 → 3 changes plane once, in city 1, and costs 100 + 600 = 700. On the right, the teal route 0 → 1 → 2 → 3 costs 100 + 100 + 200 = 400, which is cheaper. But it changes plane in city 1 and again in city 2, which is 2 stops, and k = 1
The cheapest route is not always allowed, then. How do we find the cheapest route among the ones that are short enough?
Count flights instead of stops. Every stop sits between two flights, so a trip with kk + 1dstk + 1
That can be worked out one flight at a time. With no flights, the trip is still in city 0, at price 0. With at most one flight, the flight 0 → 1 reaches city 1 for 100. With at most two, each of those prices can be extended by one more flight: from city 1, the flight to 2 gives 200 and the flight to 3 gives 700. The table below has one row per number of flights allowed, and "none" means no route reaches that city yet.
| Flights allowed | city 0 | city 1 | city 2 | city 3 |
|---|---|---|---|---|
| 0 | 0 | none | none | none |
| at most 1 | 0 | 100 | none | none |
| at most 2 | 0 | 100 | 200 | 700 |
| at most 3 | 0 | 100 | 200 | 400 |
The row "at most 2" has 700 for city 3, the answer for k = 1kk + 1
Keeping a best price for every city and improving it by trying every flight in rounds is the Bellman-Ford algorithm. In its usual form it runs until no price improves. Here it stops after k + 1
Solution Approach
Turning the rows into code means settling three things: why the usual cheapest-route method does not fit, how one round adds exactly one flight, and what price a city has before any route reaches it.
The usual cheapest-route method
Why not use Dijkstra's algorithm, the usual way to find cheapest routes? It grows routes from src
Rounds avoid that problem. Every price in the row "at most 2" uses at most two flights, because only two rounds have run, so the limit holds without counting flights per route.
One round, one more flight
What does one round do? It looks at every flight [from, to, price]fromtoflights
There is a catch inside a round. In Example 2 with k = 0
Cities not reached yet
What price does a city have before any route reaches it? It needs a value that loses every comparison, so the code uses Integer.MAX_VALUEintINFInteger.MAX_VALUE + 100
Java Solution
The method findCheapestPrice
- First, make an array
with one price per city, fill it withcost , and setINF to 0, since the trip starts there for free.cost[src] - Run
rounds with a loop whose counterk + 1 goes from 0 toround .k - At the start of each round, copy
into a new arraycost withnext . The round reads fromcost.clone() and writes intocost .next - Inside, a second loop goes over every flight
and splits it intof ,from andto . Ifprice is notcost[from] andINF is belowcost[from] + price , store that lower price innext[to] .next[to] - When the flights are done,
becomesnext for the following round.cost - After the last round, return
, or -1 if it is stillcost[dst] .INF
The maink = 2k = 0k = 0
import java.util.Arrays;
public class CheapestFlightsWithinKStops {
public static int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {
final int INF = Integer.MAX_VALUE; // "not reached yet"
int[] cost = new int[n];
Arrays.fill(cost, INF);
cost[src] = 0;
// k stops means at most k + 1 flights, so k + 1 rounds
for (int round = 0; round <= k; round++) {
int[] next = cost.clone(); // write here, read the old prices
for (int[] f : flights) {
int from = f[0], to = f[1], price = f[2];
if (cost[from] != INF && cost[from] + price < next[to]) {
next[to] = cost[from] + price; // one more flight, a lower price
}
}
cost = next;
}
return cost[dst] == INF ? -1 : cost[dst];
}
public static void main(String[] args) {
int[][] ex1 = {{0, 1, 100}, {1, 2, 100}, {2, 0, 100}, {1, 3, 600}, {2, 3, 200}};
int[][] ex2 = {{0, 1, 100}, {1, 2, 100}, {0, 2, 500}};
System.out.println("Example 1, k = 1: " + findCheapestPrice(4, ex1, 0, 3, 1));
System.out.println("Example 2, k = 1: " + findCheapestPrice(3, ex2, 0, 2, 1));
System.out.println("Example 1, k = 2: " + findCheapestPrice(4, ex1, 0, 3, 2));
System.out.println("Example 1, k = 0: " + findCheapestPrice(4, ex1, 0, 3, 0));
System.out.println("Example 2, k = 0: " + findCheapestPrice(3, ex2, 0, 2, 0));
System.out.println("src = dst: " + findCheapestPrice(3, ex2, 1, 1, 0));
System.out.println("From 1 to 2: " + findCheapestPrice(3, ex2, 1, 2, 0));
System.out.println("No way back: " + findCheapestPrice(3, ex2, 2, 0, 2));
}
}
Running it prints:
Example 1, k = 1: 700
Example 2, k = 1: 200
Example 1, k = 2: 400
Example 1, k = 0: -1
Example 2, k = 0: 500
src = dst: 0
From 1 to 2: 100
No way back: -1
The examples give 700 and 200, as expected. In the line Example 1, k = 2: 400k = 0
That 500 depends on the copy. A version that writes new prices straight into costnext
The line src = dst: 0From 1 to 2: 100INFINF
Complexity
The work is k + 1
- Time: O((k + 1) × (n + m)) for
cities and m flights, because each of then rounds copies thek + 1 prices inton and then checks each flight once.next - Space: O(n), because only two price arrays,
andcost , are alive at a time, and the flights are read where they are.next
When there is no limit on stops, the cheapest route can be found with