Page 30 • Dynamic Programming / Graph

Bellman-Ford Algorithm

Single-source shortest path using V−1 relaxation rounds, followed by negative cycle detection. Works with negative edge weights.

Interactive Graph Dry Run
Click “Start” to initialize distances.
Negative cycle: not checked
current edgerelaxed edge / updated nodenegative-cycle evidencenormal edge
Algorithm Steps
  1. Initialize source distance as 0 and all other distances as ∞.
  2. Repeat edge relaxation exactly V−1 times.
  3. Run one extra pass over all edges.
  4. If any distance still improves, a negative weight cycle exists.
Complexity

Time complexity: O(VE)
Space complexity: O(V)
Useful when negative edge weights are present, unlike Dijkstra’s basic form.

Pseudocode
BellmanFord(G, source): for each vertex v: dist[v] = ∞ parent[v] = NIL dist[source] = 0 for i = 1 to |V| - 1: for each edge (u, v, w): if dist[u] + w < dist[v]: dist[v] = dist[u] + w parent[v] = u for each edge (u, v, w): if dist[u] + w < dist[v]: report "negative weight cycle exists"