Graph Theory37 sections · 1633 units
Open in Course

LeetCode 787 Cheapest Flights Within K Stops - Layer-by-Layer Relaxation

(Limiting path length)

Standard Bellman-Ford runs n1n-1 iterations to find shortest paths with at most n1n-1 edges. Here, you run k+1k+1 iterations because at most kk stops means at most k+1k+1 flights. Use two distance arrays: distdist (current layer) and prev (previous layer). In each iteration, relax edges using prev and write results to distdist.

Copy distdist to prev at the start of each iteration. This prevents using the same layer's updates within one iteration, which would allow longer paths than intended. Each iteration extends paths by exactly one edge.