Graph Theory37 sections · 1633 units
Open in Course

LeetCode 787 Cheapest Flights Within K Stops - Implementation

(Pseudocode walkthrough)

Here is the solution:

dist := [inf] * n
dist[src] := 0
for round from 1 to k + 1
    prev := copy of dist
    for (u, v, w) in edges
        if prev[u] + w < dist[v] then
            dist[v] := prev[u] + w
return dist[dst] if dist[dst] != inf else -1

Copying distdist to prev at the start of each iteration keeps layers separate. Reading from prev and writing to distdist ensures each iteration represents exactly one additional edge.

This runs in O(VE)O(VE) time and uses O(V)O(V) space.