Algo-Sim › Advanced Graphs

Cheapest Flights Within K Stops

Medium · Advanced Graphs · step through it in Java, Python and C++ on your own input

Find the cheapest price from src to dst using at most k stops. Level-by-level BFS: each level is one more flight.

Problem

There are n cities and directed flights [from, to, price]. Return the cheapest total price to fly from src to dst using at most k stops in between (so at most k + 1 flights), or -1 if no such route exists.

Constraints

Edge cases to test

Follow-up questions

Why not plain Dijkstra?
The cheapest route may use too many stops, and a more expensive one with fewer stops may be needed; the state must include stops used.
What is the Bellman–Ford view?
Run k + 1 rounds of edge relaxation, each from a copy of the previous distances: O(k·E).

Solution

Java

public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {
    List<List<int[]>> adj = new ArrayList<>();
    for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
    for (int[] f : flights) adj.get(f[0]).add(new int[] { f[1], f[2] });
    int[] dist = new int[n];
    Arrays.fill(dist, Integer.MAX_VALUE);
    dist[src] = 0;
    Queue<int[]> queue = new ArrayDeque<>();
    queue.offer(new int[] { src, 0 });
    int stops = 0;
    while (!queue.isEmpty() && stops <= k) {
        int size = queue.size();
        for (int s = 0; s < size; s++) {
            int[] cur = queue.poll();
            for (int[] e : adj.get(cur[0])) {
                int price = cur[1] + e[1];
                if (price < dist[e[0]]) {
                    dist[e[0]] = price;
                    queue.offer(new int[] { e[0], price });
                }
            }
        }
        stops++;
    }
    return dist[dst] == Integer.MAX_VALUE ? -1 : dist[dst];
}

Python

from collections import deque


def find_cheapest_price(n, flights, src, dst, k):
    adj = [[] for _ in range(n)]
    for u, v, w in flights:
        adj[u].append((v, w))
    dist = [float("inf")] * n
    dist[src] = 0
    queue = deque([(src, 0)])
    stops = 0
    while queue and stops <= k:
        for _ in range(len(queue)):
            node, cost = queue.popleft()
            for nxt, w in adj[node]:
                price = cost + w
                if price < dist[nxt]:
                    dist[nxt] = price
                    queue.append((nxt, price))
        stops += 1
    return -1 if dist[dst] == float("inf") else dist[dst]

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int findCheapestPrice(int n, vector<vector<int>> &flights, int src, int dst, int k) {
        vector<vector<vector<int>>> adj = {};
        for (int i = 0; i < n; i++)
            adj.push_back({});
        for (vector<int> &f : flights)
            adj[f[0]].push_back(vector<int>{f[1], f[2]});
        vector<int> dist = vector<int>(n);
        fill(dist.begin(), dist.end(), INT_MAX);
        dist[src] = 0;
        deque<vector<int>> queue = {};
        queue.push_back(vector<int>{src, 0});
        int stops = 0;
        while (!queue.empty() && stops <= k) {
            int size = int(queue.size());
            for (int s = 0; s < size; s++) {
                vector<int> cur = queue.front();
                queue.pop_front();
                for (vector<int> &e : adj[cur[0]]) {
                    int price = cur[1] + e[1];
                    if (price < dist[e[0]]) {
                        dist[e[0]] = price;
                        queue.push_back(vector<int>{e[0], price});
                    }
                }
            }
            stops++;
        }
        return dist[dst] == INT_MAX ? -1 : dist[dst];
    }
};

More Advanced Graphs problems