G27
Self-checkedTier 1 13 min readalgo.sssp-bellman-ford

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, Θ(VE)\Theta(VE), 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 00. If one is reachable from the source and can reach a vertex vv, then δ(s,v)=−∞\delta(s, v) = -\infty (there is no shortest path to vv). If there is no negative cycle on any path from ss, shortest paths exist, are simple (no repeated vertex, so they have at most V−1V - 1 edges), even with negative edges.

Bellman-Ford algorithm. dist[s]=0\text{dist}[s] = 0, all others ∞\infty. Repeat V−1V - 1 times a pass: relax every edge u→vu \to v 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 ss; 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 0→1 (5)0 \to 1\,(5), 0→2 (4)0 \to 2\,(4), 1→3 (3)1 \to 3\,(3), 2→1 (−2)2 \to 1\,(-2), 2→3 (6)2 \to 3\,(6), 3→4 (2)3 \to 4\,(2), 1→4 (9)1 \to 4\,(9). Every edge is examined in each pass; the relaxed ones are marked.

Bellman-Ford: relax every edge, repeat until nothing changes

Real run

C source

1#include <stdio.h>
2
3#define N 5
4#define INF 1000000
5
6struct edge {
7 int u, v, w;
8};
9
10/* returns 1 if a negative cycle is reachable from src; otherwise dist[] holds the shortest distances */
11int bellman_ford(const struct edge e[], int m, int src, int dist[], int parent[]) {
12 for (int v = 0; v < N; v++) {
13 dist[v] = INF;
14 parent[v] = -1;
15 }
16 dist[src] = 0;
17 for (int pass = 1; pass <= N - 1; pass++) {
18 int changed = 0;
19 for (int i = 0; i < m; i++) {
20 int cand = dist[e[i].u] < INF ? dist[e[i].u] + e[i].w : INF;
21 if (dist[e[i].u] < INF && cand < dist[e[i].v]) {
22 dist[e[i].v] = cand;
23 parent[e[i].v] = e[i].u;
24 changed = 1;
25 }
26 }
27 if (!changed) {
28 break;
29 }
30 }
31 for (int i = 0; i < m; i++) {
32 if (dist[e[i].u] < INF && dist[e[i].u] + e[i].w < dist[e[i].v]) {
33 return 1;
34 }
35 }
36 return 0;
37}

edge i: from

0
0
0
1
1
2
2
3
2
4
3
5
1
6

edge i: to

1
0
2
1
3
2
1
3
3
4
4
5
4
6

edge i: weight

5
0
4
1
3
2
-2
3
6
4
2
5
9
6

dist[v] (blank = infinity)

0
1
2
3
4

parent[v]

0
1
2
3
4

State

pass 0 (at most 4 are ever needed), edges examined so far = 0

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.

1 / 37
A directed graph with 5 vertices and 7 edges (one of weight -2), in the order of the edge list, is set up by hidden driver code. bellman_ford() is the exact code that runs. Produced by: real execution: every array, stack, matrix and list in the picture is read from the running program's memory at each step. Apple clang version 21.0.0 (clang-2100.1.1.101). gcc -O0 -o prog prog.c && ./prog

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 4→14 \to 1 of weight −8-8 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: yes

Bellman-Ford pass by pass (no negative cycle): start

Computed by a script, not typed
dist 0dist 1dist 2dist 3dist 4something 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.

0 / 4
computed by script: the quantities are measured by running C, or evaluated, one row at a time. python3 scripts/gen-algo-paths-traces.py

After pass 11 the distances are 0,2,4,8,100, 2, 4, 8, 10: the edge 2→12 \to 1 of weight −2-2 improved vertex 11 from 55 to 22 after the edge 1→31 \to 3 had already used the old value 55. Pass 22 repairs this: 33 becomes 55 and 44 becomes 77. Pass 33 changes nothing, so the algorithm stops, although up to V−1=4V - 1 = 4 passes are allowed. The result is 0,2,4,5,70, 2, 4, 5, 7.

Why V−1V - 1 passes are enough

A shortest path from ss to vv has at most V−1V - 1 edges (it is simple). Consider its edges in order, s=v0→v1→⋯→vk=vs = v_0 \to v_1 \to \cdots \to v_k = v. After pass 11, dist[v1]\text{dist}[v_1] is correct (the edge s→v1s \to v_1 was relaxed, and dist[s]\text{dist}[s] was already correct). After pass 22, dist[v2]\text{dist}[v_2] is correct, and so on: after pass ii the distance of the ii-th vertex of the path is correct, whatever the order of the edges inside the passes. So V−1V - 1 passes make all distances correct. More precisely, after kk passes dist[v]\text{dist}[v] is at most the weight of the best walk from ss to vv with at most kk 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 V−1V - 1 passes.

Negative cycles

If a negative cycle is reachable, no distance ever settles: every trip around the cycle lowers something. After V−1V - 1 passes some edge can still be relaxed. The second graph shows it; the distances of vertices 11, 33, 44 keep dropping.

Bellman-Ford with a negative cycle: the distances never settle: start

Computed by a script, not typed
dist 0dist 1dist 2dist 3dist 4something 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.

0 / 5
computed by script: the quantities are measured by running C, or evaluated, one row at a time. python3 scripts/gen-algo-paths-traces.py

The cycle 1→3→4→11 \to 3 \to 4 \to 1 has weight 3+2−8=−33 + 2 - 8 = -3. In pass 44 (the last allowed) the distance of vertex 11 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 EE edges: Θ(E)\Theta(E); there are at most V−1V - 1 passes (plus the check): Θ(VE)\Theta(VE) in the worst case, space Θ(V)\Theta(V) besides the graph. On a dense graph E≈V2E \approx V^2 this is Θ(V3)\Theta(V^3); 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 Θ(V+E)\Theta(V + E), 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 edgesnegative cycle detectedtime
BFSno (unit weights)-Θ(V+E)\Theta(V + E)
Dijkstrano-Θ((V+E)log⁡V)\Theta((V + E) \log V) or Θ(V2)\Theta(V^2)
Bellman-FordyesyesΘ(VE)\Theta(VE)
DAG relaxationyesno cycles at allΘ(V+E)\Theta(V + E)

Bellman-Ford is a dynamic program: let Dk(v)D_k(v) be the best walk from ss to vv with at most kk edges; then Dk(v)=min⁡(Dk−1(v),min⁡u→vDk−1(u)+w(u,v))D_k(v) = \min(D_{k-1}(v), \min_{u \to v} D_{k-1}(u) + w(u, v)), the pass-by-pass table. It also underlies the distance-vector routing protocol of networks.

Worked examples

EX 1Passes by hand

Easy

Edges in this order: s→a (4)s \to a\,(4), a→b (−2)a \to b\,(-2), s→b (3)s \to b\,(3), b→c (1)b \to c\,(1). Pass 1: a=4a = 4; b=4−2=2b = 4 - 2 = 2; the edge s→bs \to b: 33 is not better than 22; c=2+1=3c = 2 + 1 = 3. After one pass the distances are a=4a = 4, b=2b = 2, c=3c = 3. Pass 2: nothing improves: stop. Because the edges were listed in the order of the path s,a,b,cs, a, b, c, a single pass suffices. If they were listed backwards (b→cb \to c first, s→as \to a 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?

Easy

With VV vertices, at most V−1V - 1 passes plus one check pass: for V=5V = 5, 44 passes plus the check, up to 5E5E edge examinations. On the page graph the algorithm made 33 passes (2121 edge examinations, since 3×7=213 \times 7 = 21) because pass 33 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

Medium

Edges, in this order: s→a (0)s \to a\,(0), a→b (1)a \to b\,(1), b→c (−3)b \to c\,(-3), c→a (1)c \to a\,(1). The cycle a→b→c→aa \to b \to c \to a weighs 1−3+1=−1<01 - 3 + 1 = -1 < 0. Starting from ss: pass 1: a=0a = 0, b=1b = 1, c=−2c = -2, then c→ac \to a gives a=−1a = -1 (in the same pass if the edge order allows). Pass 2: b=0b = 0, c=−3c = -3, a=−2a = -2; each further pass lowers all three by 11. After V−1=3V - 1 = 3 passes an edge can still be relaxed: negative cycle reported.

EX 4DAG shortest paths with negative edges

Medium

DAG s→a (3)s \to a\,(3), s→b (1)s \to b\,(1), b→a (−1)b \to a\,(-1), a→c (2)a \to c\,(2). A topological order: s,b,a,cs, b, a, c. Relax in this order: ss: a=3a = 3, b=1b = 1. bb: a=min⁡(3,1−1)=0a = \min(3, 1 - 1) = 0. aa: c=2c = 2. Distances s=0s = 0, b=1b = 1, a=0a = 0, c=2c = 2 in one sweep, Θ(V+E)\Theta(V + E), 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 Θ(VE)\Theta(VE): true (worst case). (c) A shortest path with negative edges and no negative cycle has at most V−1V - 1 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: V−1V - 1. (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 kk passes are the shortest paths using at most kk edges: only an upper bound: they may already be better (relaxations within a pass can use new values).

Cheat box

Cheat box

  • Bellman-Ford: dist[s]=0\text{dist}[s] = 0; repeat V−1V - 1 times: relax every edge. Then one more pass: any improvement ⇒\Rightarrow negative cycle reachable from ss.
  • Handles negative edges. Θ(VE)\Theta(VE) time, Θ(V)\Theta(V) extra space. Stop early after a pass with no change.
  • Why V−1V - 1: a shortest path is simple, so it has at most V−1V - 1 edges; pass ii fixes the ii-th vertex of any shortest path.
  • After kk passes dist ≤\le best walk with at most kk edges.
  • Undirected negative edge = negative cycle. DAG: relax in topological order, Θ(V+E)\Theta(V + E), negative edges allowed.
  • Dijkstra: no negative edges; Floyd-Warshall: all pairs, Θ(V3)\Theta(V^3).

Traps and GATE patterns

Connections

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

year not read yetQ1 · page 113 of the book
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
GATE 2026 · Set 2 · MCQ · 2 marksQ3 · page 113 of the book
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)
year not read yetQ16 · page 115 of the book
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
GATE 2013 · MCQ · 1 markQ28 · page 117 of the book
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)
year not read yetQ35 · page 119 of the book
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 V=8V = 8 vertices and no negative cycle?

Show answer

V−1=7V - 1 = 7.

Question 2

How does Bellman-Ford recognise a negative cycle?

Show answer

After V−1V - 1 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 answer

Θ(VE)\Theta(VE).

Question 4

Can a graph with a negative edge but no negative cycle have shortest paths?

Show answer

Yes; Bellman-Ford finds them (Dijkstra may fail).

Revision card

One-screen revision

  • V−1V - 1 passes of relaxing all edges; one more pass detects a negative cycle reachable from ss.
  • Θ(VE)\Theta(VE); negative edges allowed; early stop when a pass changes nothing.
  • Shortest path simple ⇒\Rightarrow at most V−1V - 1 edges; pass ii fixes the ii-th vertex of any shortest path.
  • Undirected negative edge = negative cycle. DAG: topological order, Θ(V+E)\Theta(V + E).

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)