Cheapest Flights Within K Stops

Bellman-Ford limited to k+1 edges — relax k+1 times.

Medium
Time O(k * E) Space O(n)
LeetCode
4 min read
dp graph bellman-ford

Problem#

Given flights (directed weighted edges), find the cheapest price from src to dst using at most k stops (so k + 1 edges).

Examples#

  • n=3, flights=[[0,1,100],[1,2,100],[0,2,500]], src=0, dst=2, k=1200

Constraints#

  • 1 <= n <= 100, 0 <= k <= n.

Approach#

Bellman-Ford with k + 1 rounds. dp[v] = best known cost to reach v using ≤ r edges (after round r). Each round, snapshot previous dp, relax every flight using the snapshot. After k + 1 rounds, return dp[dst] or -1.

Solution#

Cheapest Flights Within K Stops
class Solution {
public:
int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int k) {
const int INF = INT_MAX;
vector<int> dp(n, INF);
dp[src] = 0;
for (int r = 0; r <= k; ++r) {
vector<int> prev = dp;
for (auto& f : flights) {
int u = f[0], v = f[1], w = f[2];
if (prev[u] != INF) dp[v] = min(dp[v], prev[u] + w);
}
}
return dp[dst] == INF ? -1 : dp[dst];
}
};

Editorial#

The snapshot is critical — without it, we’d accidentally use 2 edges in a single round (chained relaxations). The round count k + 1 corresponds to “at most k stops = at most k + 1 edges”.

Complexity#

  • Time: O(k * E).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.