prices · frozen for this round (read)
tmpPrices · this round's results (written)
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) { int inf = Integer.MAX_VALUE; int[] prices = new int[n]; Arrays.fill(prices, inf); prices[src] = 0; for (int i = 0; i <= k; i++) { // round i: <= i+1 flights int[] tmpPrices = prices.clone(); for (int[] f : flights) { int s = f[0]; int d = f[1]; int p = f[2]; if (prices[s] == inf) { continue; } if (prices[s] + p < tmpPrices[d]) { tmpPrices[d] = prices[s] + p; } } prices = tmpPrices; } return prices[dst] == inf ? -1 : prices[dst];}
- i
- —
- (s, d, p)
- —
- prices[s] + p
- —
- tmpPrices[d]
- —
Why it works
- Brute force enumerates every route of at most k + 1 flights by DFS: up to O(dᵏ⁺¹) for out-degree d.
- Round i finds the cheapest routes of at most i + 1 flights. Each round extends every known route by exactly one flight. After k + 1 rounds,
prices[dst]is the cheapest route with at most k stops. - Why the copy: every relaxation reads the frozen
pricesand writestmpPrices. Writing straight intopriceswould let one round chain several flights, quietly breaking the stop limit. Thecontinueon an unreachable city also protects the sum:Integer.MAX_VALUE + pwould overflow to a negative number. In the "why the copy" preset, the route 0→3→1→4→2 costs 6 but needs 4 flights; with k = 2 the answer must be 7. - Cost: k + 1 rounds over all E flights: O(k · E) time, two arrays of n prices: O(n) space.
- Pitfall: plain Dijkstra ignores the stop count: it settles a city by its cheapest price even if that route used too many stops. Related: Network Delay Time (743) is the unconstrained Dijkstra version.