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
- 1 ≤ n ≤ 100
- 0 ≤ flights.length ≤ n · (n − 1) / 2
- 1 ≤ price ≤ 10⁴
- 0 ≤ src, dst, k < n and src ≠ dst
- Plain Dijkstra ignores the stop limit
Edge cases to test
- src == dst:
0 - No route within k stops:
-1 - A cheaper route with more stops than allowed
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
- Network Delay Time (Medium)
- Evaluate Division (Medium)
- Course Schedule II (Medium)
- Alien Dictionary (Hard)
- Redundant Connection (Medium)
- Number of Connected Components (Union-Find) (Medium)
- Accounts Merge (Medium)
- Minimum Spanning Tree (Kruskal) (Medium)
- Minimum Spanning Tree (Prim) (Medium)
- Min Cost to Connect All Points (Medium)
- Bellman-Ford (negative weights) (Medium)
- Find the City (Floyd-Warshall) (Medium)
- Critical Connections in a Network (Hard)
- Articulation Points (Cut Vertices) (Hard)
- Strongly Connected Components (Hard)
- Reconstruct Itinerary (Hard)
- Minimum Height Trees (Medium)