Loading algorithms…
Loading visualizer…
Single-source shortest paths that handle negative edge weights and detect negative-weight cycles.
Dijkstra assumes every edge relaxes distance monotonically — once it marks a node as "final," it never revisits it. With negative weights, that assumption breaks. Bellman-Ford instead relaxes every edge V−1 times so cheaper paths can propagate through chains that Dijkstra would have ignored. Compare with Dijkstra →
Bellman-Ford is a single-source shortest-path algorithm that, unlike Dijkstra, handles negative edge weights and can detect negative-weight cycles.
0 and all other distances to ∞.(u, v, w), if dist[u] + w < dist[v], update dist[v] and record prev[v] = u.A shortest path in a graph with no negative cycles visits at most V − 1 edges. Each iteration of the outer loop can lengthen the shortest known path by at most one edge, so V−1 iterations are sufficient to propagate the cheapest path to every node.
⚠️ Negative cycles: If the graph contains a cycle whose total weight is negative, you can keep walking around it forever to drive the distance to −∞. Bellman-Ford detects this in the V-th pass and reports that the shortest path is undefined.
Bellman-Ford handles them. Dijkstra assumes non-negative weights — a single negative edge can produce incorrect results.
Bellman-Ford detects them explicitly. Dijkstra quietly loops forever or returns −∞.
Bellman-Ford is O(V·E) in the worst case. Dijkstra with a heap is O((V+E) log V) — faster when all weights are non-negative.
Click nodes to set source/target · Drag nodes to rearrange layout · Use controls to step through V−1 relaxation passes