Bellman-Ford
Single-source shortest paths when edge weights may be negative: relax every edge V - 1 times, why V - 1 passes suffice (a shortest path has at most V - 1 edges), the early stop when a pass changes nothing, detection of negative cycles by one more pass, running time O(VE), why undirected negative edges are negative cycles, and when to use it instead of Dijkstra.
Why it exists
Dijkstra's algorithm fails as soon as one edge weight is negative, yet negative weights are natural: a gain, a refund, a rebate, the logarithm of an exchange rate. Bellman-Ford handles them. It is slower, , because it is simple and cautious: it relaxes every edge again and again until nothing improves. It also answers a question Dijkstra cannot: is there a negative cycle (a cycle of negative total weight), in which case shortest paths do not exist because one can go round and round to get ever cheaper? GATE asks for the distances after a given number of passes, the number of passes needed, the running time, and negative cycle detection.
Prerequisites
You need relaxation, shortest-path distance and Dijkstra's algorithm (Dijkstra).
Precise definitions
Negative cycle. A directed cycle whose edge weights sum to less than . If one is reachable from the source and can reach a vertex , then (there is no shortest path to ). If there is no negative cycle on any path from , shortest paths exist, are simple (no repeated vertex, so they have at most edges), even with negative edges.
Bellman-Ford algorithm. , all others . Repeat times a pass: relax every edge of the graph once (in any fixed order). Then do one more pass without changing anything: if some edge can still be relaxed, a negative cycle is reachable from ; otherwise the distances are the shortest-path distances. A pass in which nothing changes lets the algorithm stop early: nothing will change in later passes either.
Walk. A path that may repeat vertices. Relaxation passes compute the best walk with at most a given number of edges.
How it works
The animation runs the real code on five vertices and the edge list , , , , , , . Every edge is examined in each pass; the relaxed ones are marked.
Bellman-Ford: relax every edge, repeat until nothing changes
Real runC source
edge i: from
edge i: to
edge i: weight
dist[v] (blank = infinity)
parent[v]
State
Blue = the position this step is working on, amber = a position being compared, red = positions just swapped, green = finished or in its final place, a filled blue cell = a value just placed, faded = not part of the structure at this step.
Step 1
A weighted directed graph with a negative edge (2 -> 1 of weight -2). Shortest distances from vertex 0.
The program below runs the same algorithm and prints the distances after each pass. It is then run on a second graph in which the edge of weight has been added.
#include <stdio.h>
#define N 5
#define INF 1000000
struct edge { int u, v, w; };
static void show(const int dist[]) {
for (int v = 0; v < N; v++) {
if (dist[v] >= INF) printf(" inf");
else printf(" %3d", dist[v]);
}
}
/* returns 1 if a negative cycle is reachable from src */
static int bellman_ford(const struct edge e[], int m, int src, int dist[], int verbose) {
for (int v = 0; v < N; v++) dist[v] = INF;
dist[src] = 0;
for (int pass = 1; pass <= N - 1; pass++) {
int changed = 0;
for (int i = 0; i < m; i++) {
if (dist[e[i].u] < INF && dist[e[i].u] + e[i].w < dist[e[i].v]) {
dist[e[i].v] = dist[e[i].u] + e[i].w;
changed = 1;
}
}
if (verbose) { printf("pass %d:", pass); show(dist); printf("%s\n", changed ? "" : " (no change: stop)"); }
if (!changed) break;
}
for (int i = 0; i < m; i++)
if (dist[e[i].u] < INF && dist[e[i].u] + e[i].w < dist[e[i].v]) return 1;
return 0;
}
int main(void) {
struct edge e[7] = {{0, 1, 5}, {0, 2, 4}, {1, 3, 3}, {2, 1, -2}, {2, 3, 6}, {3, 4, 2}, {1, 4, 9}};
int dist[N];
printf("graph 1 (no negative cycle):\n");
int bad = bellman_ford(e, 7, 0, dist, 1);
printf("negative cycle reachable: %s\n", bad ? "yes" : "no");
struct edge f[8] = {{0, 1, 5}, {0, 2, 4}, {1, 3, 3}, {2, 1, -2}, {2, 3, 6}, {3, 4, 2}, {1, 4, 9}, {4, 1, -8}};
printf("graph 2 (the edge 4 -> 1 of weight -8 closes the cycle 1, 3, 4 of weight -3):\n");
bad = bellman_ford(f, 8, 0, dist, 1);
printf("negative cycle reachable: %s\n", bad ? "yes" : "no");
return 0;
}graph 1 (no negative cycle):
pass 1: 0 2 4 8 10
pass 2: 0 2 4 5 7
pass 3: 0 2 4 5 7 (no change: stop)
negative cycle reachable: no
graph 2 (the edge 4 -> 1 of weight -8 closes the cycle 1, 3, 4 of weight -3):
pass 1: 0 2 4 8 10
pass 2: 0 -1 4 5 7
pass 3: 0 -4 4 2 4
pass 4: 0 -7 4 -1 1
negative cycle reachable: yesBellman-Ford pass by pass (no negative cycle): start
Computed by a script, not typed| dist 0 | dist 1 | dist 2 | dist 3 | dist 4 | something changed? | |
|---|---|---|---|---|---|---|
| start | ||||||
| after pass 1 | ||||||
| after pass 2 | ||||||
| after pass 3 |
Step 0
Distances from vertex 0 after each pass over all edges in list order. The edge 2 -> 1 (weight -2) makes vertex 1 reachable more cheaply through 2.
After pass the distances are : the edge of weight improved vertex from to after the edge had already used the old value . Pass repairs this: becomes and becomes . Pass changes nothing, so the algorithm stops, although up to passes are allowed. The result is .
Why passes are enough
A shortest path from to has at most edges (it is simple). Consider its edges in order, . After pass , is correct (the edge was relaxed, and was already correct). After pass , is correct, and so on: after pass the distance of the -th vertex of the path is correct, whatever the order of the edges inside the passes. So passes make all distances correct. More precisely, after passes is at most the weight of the best walk from to with at most edges (checked). The order of the edges inside a pass can make convergence faster but not slower: a path graph whose edges are listed in the worst order (last edge first) needs exactly passes.
Negative cycles
If a negative cycle is reachable, no distance ever settles: every trip around the cycle lowers something. After passes some edge can still be relaxed. The second graph shows it; the distances of vertices , , keep dropping.
Bellman-Ford with a negative cycle: the distances never settle: start
Computed by a script, not typed| dist 0 | dist 1 | dist 2 | dist 3 | dist 4 | something changed? | |
|---|---|---|---|---|---|---|
| start | ||||||
| after pass 1 | ||||||
| after pass 2 | ||||||
| after pass 3 | ||||||
| after pass 4 |
Step 0
With a negative cycle every extra pass lowers some distances: after V - 1 = 4 passes the algorithm checks the edges once more; an edge that can still be relaxed proves a negative cycle.
The cycle has weight . In pass (the last allowed) the distance of vertex is still going down, and the extra check pass finds an edge that can be relaxed: negative cycle reported. The detection is exact: such an edge exists if and only if a negative cycle is reachable from the source (tested against a brute-force enumeration of all simple cycles).
Undirected graphs. An undirected edge is two directed edges, so an undirected edge of negative weight is already a negative cycle (go back and forth). Bellman-Ford cannot give shortest paths in an undirected graph with a negative edge.
Running time and space
Each pass examines all edges: ; there are at most passes (plus the check): in the worst case, space besides the graph. On a dense graph this is ; with an early stop the typical running time is much smaller. A queue-based version that only re-examines the out-edges of vertices whose distance has just improved is faster in practice but has the same worst case.
Shortest paths in a directed acyclic graph
If the graph is a DAG, relax the edges once in the order of a topological sort of the sources of the edges: a vertex is relaxed after all its predecessors are final. Time , and negative weights are allowed (there are no cycles). This gives, for example, the longest path in a DAG by negating the weights.
Which algorithm when
| negative edges | negative cycle detected | time | |
|---|---|---|---|
| BFS | no (unit weights) | - | |
| Dijkstra | no | - | or |
| Bellman-Ford | yes | yes | |
| DAG relaxation | yes | no cycles at all |
Bellman-Ford is a dynamic program: let be the best walk from to with at most edges; then , the pass-by-pass table. It also underlies the distance-vector routing protocol of networks.
Worked examples
EX 1Passes by hand
EasyEdges in this order: , , , . Pass 1: ; ; the edge : is not better than ; . After one pass the distances are , , . Pass 2: nothing improves: stop. Because the edges were listed in the order of the path , a single pass suffices. If they were listed backwards ( first, last), three passes that change something would be needed (and a fourth to see that nothing changes) for the same graph.
EX 2How many passes can be needed?
EasyWith vertices, at most passes plus one check pass: for , passes plus the check, up to edge examinations. On the page graph the algorithm made passes ( edge examinations, since ) because pass found no change. The worst case for a given graph depends on the order of the edge list, not only on the graph.
EX 3Detect a negative cycle
MediumEdges, in this order: , , , . The cycle weighs . Starting from : pass 1: , , , then gives (in the same pass if the edge order allows). Pass 2: , , ; each further pass lowers all three by . After passes an edge can still be relaxed: negative cycle reported.
EX 4DAG shortest paths with negative edges
MediumDAG , , , . A topological order: . Relax in this order: : , . : . : . Distances , , , in one sweep, , although there is a negative edge.
EX 5Typical statements
GATE level(a) Bellman-Ford detects a negative cycle reachable from the source: true. (b) It runs in : true (worst case). (c) A shortest path with negative edges and no negative cycle has at most edges: true. (d) Dijkstra's algorithm may be used on a graph with negative edges if there is no negative cycle: false. (e) Number of passes after which the distances are final, at most: . (f) Bellman-Ford works for undirected graphs with a negative edge: no shortest path exists (the edge is a negative 2-cycle). (g) Distances after exactly passes are the shortest paths using at most edges: only an upper bound: they may already be better (relaxations within a pass can use new values).
Cheat box
Cheat box
- Bellman-Ford: ; repeat times: relax every edge. Then one more pass: any improvement negative cycle reachable from .
- Handles negative edges. time, extra space. Stop early after a pass with no change.
- Why : a shortest path is simple, so it has at most edges; pass fixes the -th vertex of any shortest path.
- After passes dist best walk with at most edges.
- Undirected negative edge = negative cycle. DAG: relax in topological order, , negative edges allowed.
- Dijkstra: no negative edges; Floyd-Warshall: all pairs, .
Traps and GATE patterns
Connections
Builds on
Across subjects
No cross-subject links yet.
Bellman-Ford contrasts with Dijkstra (faster, no negative weights) and with Floyd-Warshall (all pairs); it is a dynamic program over the number of edges (dynamic programming).
PYQs
5 previous year questions from your book. I re-solved each one myself (1 by running or simulating, 4 by reasoning only); the book's key is shown next to my answer. All PYQs
Let G(V,E) be an undirected, edge-weighted graph with integer weights. The weight of a path is the sum of the weights of the edges in that path. The length of a path is the number of edges in that path. Let s∈V be a vertex in G. For every u∈V and for every k ≥0, let dk(u) denote the weight of a shortest path (in terms of weight) from s to u of length at most k. If there is no path from s to u of length at most k, then dk(u)=∞.Consider the statements: S1: For every k ≥0 and u ∈V, dk+1(u)≤dk(u). S2: For every (u,v)∈E, if (u,v) is part of a shortest path (in terms of weight) from s to v, then for every k≥ 0,dk(u)≤dk(v). Which one of the following options is correct?
- (a)Only S1 is true
- (b)Only S2 is true
- (c)Both S1 and S2 are true
- (d)Neither S1 nor S2 is true
Let G be a weighted directed acyclic graph with m edges and n vertices. Given G and a source vertex s in G, which one of the following options gives the worst case time complexity of the fastest algorithm to find the lengths of shortest paths from s to all vertices that are reachable from s in G?
- (a)Θ(m + n)
- (b)Θ(m + n log(n))
- (c)Θ(nm)
- (d)Θ(n3)
Let G = (V, E) be a directed, weighed graph with weight function w : E -> R. For some function f : V - > R, for each edge (u, v) in E, define w'(u, v) as w(u, v) + f(u) - f(v). Which one of the options completes the following sentence so that it is TRUE? "The shortest paths in G under w are shortest paths under w' too, ".
- (a)for every f : V -> R
- (b)if and only if for all u in V, f(u) is positive
- (c)if and only if for all u in V, f(u) is negative
- (d)if and only if f(u) is the distance from s to u in the graph obtained by adding a new vertex s to G and edges of zero weight from s to every vertex of G
What is the time complexity of Bellman-Ford single-source shortest path algorithm on a complete graph of n vertices?
- (a)Θ(n2)
- (b)Θ(n2log n)
- (c)Θ(n3)
- (d)Θ(n3log n)
Which of the following statement(s) is/are correct regarding Bellman-Ford shortest path algorithm? P. Always finds a negative weighted cycle, if one exists. Q. Finds whether any negative weighted cycle is reachable from the source.
- (a)P only
- (b)Q only
- (c)Both P and Q
- (d)Neither P nor Q
Self-check
Question 1
How many passes of Bellman-Ford over all edges guarantee correct distances in a graph with vertices and no negative cycle?
Show answerHide
.
Question 2
How does Bellman-Ford recognise a negative cycle?
Show answerHide
After passes an edge can still be relaxed; this happens exactly when a negative cycle is reachable from the source.
Question 3
What is the running time of Bellman-Ford?
Show answerHide
.
Question 4
Can a graph with a negative edge but no negative cycle have shortest paths?
Show answerHide
Yes; Bellman-Ford finds them (Dijkstra may fail).
Revision card
One-screen revision
- passes of relaxing all edges; one more pass detects a negative cycle reachable from .
- ; negative edges allowed; early stop when a pass changes nothing.
- Shortest path simple at most edges; pass fixes the -th vertex of any shortest path.
- Undirected negative edge = negative cycle. DAG: topological order, .
References
- ·Cormen, Leiserson, Rivest, Stein, Introduction to Algorithms (3rd edition), Section 24.1 The Bellman-Ford algorithm and Section 24.2 (single-source shortest paths in directed acyclic graphs)
- ·Sedgewick and Wayne, Algorithms (4th edition), Section 4.4 (Bellman-Ford, negative cycles)
- ·Dasgupta, Papadimitriou, Vazirani, Algorithms, Section 4.6 Shortest paths in the presence of negative edges
Verification
On 600 random directed graphs of up to 6 vertices with weights from -4 to 9, Bellman-Ford distances were compared with a brute force over ALL simple paths, and negative cycles (found by enumerating ALL simple cycles) were detected exactly when they exist; on 400 more graphs the distance after k passes was shown to be at most the best walk with at most k edges and the extra pass was shown to change something exactly when a negative cycle is reachable; a path graph with its edges in the worst order needs exactly V - 1 passes for V up to 8; shortest paths in a DAG by one pass in topological order equalled Bellman-Ford. The animation and the tables are real runs of the C code on the page. The remark about the queue-based variant is quoted from the literature and not tested. Textbook chapter references are from memory. SECOND PASS (2026-11-02, done by the assistant, not a human check): every Self-check question was solved before the printed answer was read and all agreed; the definitions, worked examples, cheat box and traps were read claim by claim and the numbers re-derived by hand or by a small script (loop counts, recurrences, merge and quicksort counts and averages, hash probes and load-factor formulas, DP tables, MST and shortest-path runs, Floyd matrices); long C programs were not re-read line by line (they are compiled and compared by npm run verify:c, and their printed outputs were checked against the prose); tables and animations are machine output and were read, not re-run; No other defect found. Status raised to self-checked; verified needs a textbook or human check.
last verified: never
My notes (saved in this browser)