Loading...
Bellman-Ford generalizes Dijkstra by working with negative edge weights and detecting negative weight cycles through repeated global relaxation passes over all edges.
Given a weighted directed graph G=(V,E) that may contain negative edge weights (but no negative cycles reachable from the source), Bellman-Ford computes the shortest path distances from a source vertex s to every other vertex. It uses at most |V|−1 passes to propagate shortest path improvements progressively along edges.
K = number of passes until convergence (K ≤ V−1). Better for sparse graphs or when shortest paths use few edges.
1BellmanFord(G, w, source):2 for each vertex v in G.V:3 dist[v] ← ∞4 parent[v] ← NIL5 dist[source] ← 06 // |V|-1 relaxation passes7 for i from 1 to |V|-1:8 updated ← false9 for each edge (u, v) in G.E:10 if dist[u] + w(u,v) < dist[v]:11 dist[v] ← dist[u] + w(u,v)12 parent[v] ← u13 updated ← true14 if not updated: // early stop optimization15 break16 // Negative cycle detection17 for each edge (u, v) in G.E:18 if dist[u] + w(u,v) < dist[v]:19 return "NEGATIVE CYCLE" // or mark cycle vertices20 return dist, parent
Aspect | Bellman-Ford | Dijkstra |
---|---|---|
Edge Weights | Negative allowed | Must be ≥ 0 |
Time Complexity | O(V·E) | O((V+E) log V) |
Data Structure | Edge list loops | Priority queue |
Negative Cycle Detection | Yes (extra pass) | No |
Early Exit Potential | Yes (no updates) | Implicit via queue exhaustion |