Cheapest Flights Within K Stops

Find the cheapest trip between two cities when the number of stops on the way is limited.

There are n cities, numbered 0 to n - 1, and a list of one-way flights. Each flight is written as [from, to, price]: it goes from city from to city to and costs price. Given a start city src, a destination dst and a number k, return the cheapest total price of a trip from src to dst with at most k stops on the way. If there is no such trip, 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
Explanation: 0 → 1 → 3 costs 700 with one stop. 0 → 1 → 2 → 3 costs 400 but needs two stops.
Example 2
Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1
Output: 200
Explanation: 0 → 1 → 2 costs 200 with one stop, less than the direct flight for 500.
Solution

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 src, and city 3, marked "end", is dst. Points joined by arrows like this form a directed graph, and with a price on every arrow it is called a weighted one.

Example 1 drawn twice: four cities 0 to 3 joined by one-way flights with prices. On the left, the route 0 to 1 to 3 takes 2 flights and 1 stop for 700, which k = 1 allows. On the right, the route 0 to 1 to 2 to 3 takes 3 flights and 2 stops for 400, too many stops.

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 allows only one. So the answer is 700.

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 k stops has k + 1 flights. The question becomes: what is the cheapest price to reach dst with at most k + 1 flights?

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 allowedcity 0city 1city 2city 3
00nonenonenone
at most 10100nonenone
at most 20100200700
at most 30100200400

The row "at most 2" has 700 for city 3, the answer for k = 1. The row "at most 3" reaches 400 through city 2, but that route has two stops, so it counts only when k is 2 or more. The answer is in the row for k + 1 flights. Each row comes from the one above by trying every flight once, and building one row is called a round.

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 rounds.

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, always extending the cheapest one found so far, and keeps one best price per city. That price forgets how many flights it took. In Example 1, city 2's best price, 200, already uses two flights, so going on from there to city 3 breaks the limit. Plain Dijkstra's algorithm takes that step anyway and reports the teal route's 400.

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] and asks whether reaching from at its best price and then taking this flight beats the best price known for to. A graph is often stored as an adjacency list, which keeps for each city the flights leaving it. A round visits every flight anyway, so the plain flights list works as it is.

There is a catch inside a round. In Example 2 with k = 0, only the direct flight is allowed, so the answer is 500. Suppose a round wrote new prices into the same array it reads. The flight 0 → 1 would set city 1 to 100, and the flight 1 → 2, later in the list, would read that 100 and set city 2 to 200. That is two flights in one round. So each round reads the prices of the round before and writes into a copy.

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_VALUE, the largest int, and names it INF, for infinity. Adding a flight's price to it is not safe. In Java, Integer.MAX_VALUE + 100 wraps around to -2,147,483,549, which would beat every real price. So a flight is tried only when its start city has been reached.

Java Solution

The method findCheapestPrice works in these steps:

  1. First, make an array cost with one price per city, fill it with INF, and set cost[src] to 0, since the trip starts there for free.
  2. Run k + 1 rounds with a loop whose counter round goes from 0 to k.
  3. At the start of each round, copy cost into a new array next with cost.clone(). The round reads from cost and writes into next.
  4. Inside, a second loop goes over every flight f and splits it into from, to and price. If cost[from] is not INF and cost[from] + price is below next[to], store that lower price in next[to].
  5. When the flights are done, next becomes cost for the following round.
  6. After the last round, return cost[dst], or -1 if it is still INF.

The main method runs both examples, then Example 1 with k = 2 and k = 0, and Example 2 with k = 0. On the flights of Example 2 it also tries a trip that starts where it ends, a trip from city 1 to city 2, and a trip from city 2 to city 0.

Java
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:

Output
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: 400, two stops are allowed, so the teal route from the picture fits and the price drops to 400. With k = 0 only direct flights count: Example 1 has none from 0 to 3, so it prints -1, while Example 2 prints 500 for its direct flight.

That 500 depends on the copy. A version that writes new prices straight into cost, without next, printed 200 for the same input, because the flights 0 → 1 and 1 → 2 chained inside one round.

The line src = dst: 0 shows a trip that is over before it starts. The line From 1 to 2: 100 is the one flight leaving city 1, and it also tests the INF check: city 0 is never reached from city 1. A version without the check added 500 to INF for the flight 0 → 2 and printed -2147483149. The last line is -1 because no flight lands in city 0 at all.

Complexity

The work is k + 1 rounds, and each round copies the prices once and looks at every flight once.

  • Time: O((k + 1) × (n + m)) for n cities and m flights, because each of the k + 1 rounds copies the n prices into next and then checks each flight once.
  • Space: O(n), because only two price arrays, cost and next, are alive at a time, and the flights are read where they are.

When there is no limit on stops, the cheapest route can be found with Dijkstra's Algorithm.