787. Cheapest Flights Within K Stops
Asked at 17Amazon45Apple43Google36Bloomberg30Microsoft30Meta28Flipkart64TikTok50Oracle35Stripe86Airbnb66Expedia54Snowflake48Snap45Intuit43Cisco37Uber30
Problem
flights[i] = [from, to, price] are one-way flights between cities 0…n − 1. Return the cheapest price from src to dst using at most k stops (so at most k + 1 flights), or −1 if there is no such route.
Example: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1 → 700 (0 → 1 → 3)
At most k stops = at most k+1 edges → run k+1 rounds of Bellman–Ford relaxation, each round relaxing from a copy of the previous distances (so one round adds at most one edge).
round 0: dist {0:0}
round 1: dist {0:0, 1:100}
round 2: dist {0:0, 1:100, 2:200, 3:700} k=1 -> answer dist[3] = 700
Complexity: O(k · E).
class Solution:
def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:
INF = float("inf")
dist = [INF] * n
dist[src] = 0
for _ in range(k + 1):
nxt = dist[:]
for u, v, w in flights:
if dist[u] + w < nxt[v]:
nxt[v] = dist[u] + w
dist = nxt
return -1 if dist[dst] == INF else dist[dst]
F = [[0, 1, 100], [1, 2, 100], [2, 0, 100], [1, 3, 600], [2, 3, 200]]
assert Solution().findCheapestPrice(4, F, 0, 3, 1) == 700
assert Solution().findCheapestPrice(3, [[0, 1, 100], [1, 2, 100], [0, 2, 500]], 0, 2, 0) == 500
class Solution {
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {
int INF = Integer.MAX_VALUE;
int[] dist = new int[n];
Arrays.fill(dist, INF);
dist[src] = 0;
for (int i = 0; i <= k; i++) {
int[] nxt = dist.clone();
for (int[] f : flights)
if (dist[f[0]] != INF && dist[f[0]] + f[2] < nxt[f[1]]) nxt[f[1]] = dist[f[0]] + f[2];
dist = nxt;
}
return dist[dst] == INF ? -1 : dist[dst];
}
}
func findCheapestPrice(n int, flights [][]int, src int, dst int, k int) int {
const inf = math.MaxInt32
dist := make([]int, n)
for i := range dist {
dist[i] = inf
}
dist[src] = 0
for round := 0; round <= k; round++ { // Bellman-Ford limited to k+1 edges
next := append([]int(nil), dist...) // relax from last round's values only
for _, f := range flights {
if dist[f[0]] != inf && dist[f[0]]+f[2] < next[f[1]] {
next[f[1]] = dist[f[0]] + f[2]
}
}
dist = next
}
if dist[dst] == inf {
return -1
}
return dist[dst]
}