Graph Theory37 sections · 1633 units
Open in Course

LeetCode 787 Cheapest Flights Within K Stops - Algorithm

(Modified Bellman-Ford)

1.1. Initialize dist[src] = 0, all others to infinity.

2.2. Repeat k+1k+1 times: copy distdist to prev, then for each edge (u,v,w)(u, v, w), if prev[u] + w < dist[v], set dist[v] = prev[u] + w.

3.3. After k+1k+1 iterations, return dist[dst] if finite, otherwise return 1-1.

The two-array approach ensures you count stops correctly. Each iteration represents one additional flight (edge) in the path.