← Visualizers
Graphs · Weighted shortest path · anti-pattern LeetCode 787

Cheapest Flights Within K Stops / visualized

Dijkstra is not merely awkward here — it is wrong. Its correctness rests on one invariant that a stop budget quietly removes: the first pop of a node is final. Add a budget and a cheap arrival that spent too many flights seals a city shut against the expensive arrival that still had budget left to finish. Bellman–Ford never claims finality: it runs k + 1 rounds, and each round relaxes every flight against a frozen snapshot of the previous round’s prices — which is what stops one round from chaining two flights.

Execution

idle
Press Run to begin.
0 / 0
Speed

Java · running line

Bellman–Ford
flight being relaxed has a finite price frozen snapshot row finalised — closed forever
Bellman–Ford: O((k+1)·E) time, O(n) space  ·  the budget turns the state from node into (node, flights used), and any algorithm that finalises on node alone — Dijkstra with a visited set — throws away the arrival that was still legal. Bellman–Ford sidesteps the whole question by counting rounds instead of settling nodes, and the prev = dist.clone() snapshot is what makes a round worth exactly one flight.