Bellman-Ford
30 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Bellman-Ford computes shortest paths on graphs with negative edge weights and detects negative weight cycles in O(V * E) time.
Why Bellman-Ford handles negative edge weights
The Bellman-Ford algorithm finds shortest paths even when some edge weights are negative, by relaxing every edge V - 1 times, and can detect negative cycles.
Dijkstra assumes that adding an edge to a path always increases its total cost. When negative edges exist, earlier finalised distances can be undercut later. Brute force search explores every simple path, requiring factorial O(V!) time.
Bellman-Ford relaxation rounds
Step 1 of 4
- distS
- 0
- distA
- inf
- distB
- inf
- distC
- inf
Example 1 · Single-Source Shortest Paths with Negative Weights
import java.util.Arrays;
public class BellmanFordDemo { public static int[] shortestPaths(int n, int[][] edges, int src) { int[] dist = new int[n]; int INF = 1_000_000_000; Arrays.fill(dist, INF); dist[src] = 0;
for (int i = 0; i < n - 1; i++) { boolean updated = false; for (int[] e : edges) { int u = e[0]; int v = e[1]; int w = e[2]; if (dist[u] != INF && dist[u] + w < dist[v]) { dist[v] = dist[u] + w; updated = true; } } if (!updated) break; } return dist; }
public static void main(String[] args) { int n = 4; // edges: {u, v, weight} int[][] edges = { {0, 1, 4}, {0, 2, 5}, {2, 1, -2}, {1, 3, 3}, {2, 3, 6} }; int[] dist = shortestPaths(n, edges, 0); System.out.println("Distances: " + Arrays.toString(dist)); }}Distances: [0, 3, 5, 6]
What this code does
- Initialises all tentative distances to infinity and sets source distance to 0.
- Relaxes every edge across V - 1 rounds with early termination if no distance updates.
- Edge (2, 1, -2) reduces dist[1] to 3, which later propagates to dist[3] = 6.
Bellman-Ford overcomes this by relaxing every edge in the graph V - 1 times. In a graph with V vertices, any simple path contains at most V - 1 edges. Each relaxation pass guarantees finding shortest paths with one additional edge. After V - 1 passes, all shortest paths are guaranteed to be fully discovered. Consider four vertices S, A, B, and C with source S. Initially, dist[S] is 0 and all other tentative distances are set to infinity. In round 1, outgoing edges from S discover distances to neighbours A and B. In round 2, the edge between B and A can lower the distance to A. In round 3, the updated distance to A propagates to C, finalising all paths.
Predict the output
Predict one relaxation pass
Read the code and pick what it prints.
Round 1 of 2
One pass over the edges, in the order listed. What is dist?
Detecting negative weight cycles and infinite arbitrage
A negative weight cycle is a closed directed loop whose edge sum is strictly negative. Traversing this cycle repeatedly reduces path cost towards negative infinity without stopping. In such graphs, a true shortest path between certain vertex pairs does not exist.
Example 2 · Detecting Negative Weight Cycles
import java.util.Arrays;
public class NegativeCycleDetectionDemo { public static boolean hasNegativeCycle(int n, int[][] edges, int src) { int[] dist = new int[n]; int INF = 1_000_000_000; Arrays.fill(dist, INF); dist[src] = 0;
for (int i = 0; i < n - 1; i++) { for (int[] e : edges) { int u = e[0]; int v = e[1]; int w = e[2]; if (dist[u] != INF && dist[u] + w < dist[v]) { dist[v] = dist[u] + w; } } }
// V-th relaxation pass for (int[] e : edges) { int u = e[0]; int v = e[1]; int w = e[2]; if (dist[u] != INF && dist[u] + w < dist[v]) { return true; // Distance can still be reduced } } return false; }
public static void main(String[] args) { int n = 4; // Contains negative cycle: 1 -> 2 (2), 2 -> 3 (2), 3 -> 1 (-5), sum = -1 int[][] edges = { {0, 1, 1}, {1, 2, 2}, {2, 3, 2}, {3, 1, -5} }; boolean cycle = hasNegativeCycle(n, edges, 0); System.out.println("Negative cycle detected: " + cycle); }}Negative cycle detected: true
What this code does
- Runs standard V - 1 relaxation iterations to establish candidate shortest paths.
- Tests all edges in round V to check if any distance can still decrease.
- Detects cycle 1 -> 2 -> 3 -> 1 having total weight 2 + 2 - 5 = -1.
Brute force cycle inspection tests all combinations of directed cycles in exponential time. Bellman-Ford detects negative cycles by running one additional relaxation round. If any distance array entry drops in the V-th round, a negative cycle exists. This single extra pass runs in linear O(E) time. Suppose vertices X and Y form a loop with edge weights 2 and -5. The loop sum is -3, reducing the path cost by 3 on every repetition. In round V, edge Y->X reduces dist[X] further. When detected, the algorithm reports that no finite shortest path exists.
Order of execution
Find a negative cycle
Tap the steps of Bellman-Ford in the order they run.
Constrained shortest paths: cheapest flights within k stops
Practical routing questions frequently bound the number of transit stops allowed. For example, find the cheapest flight from origin to destination with at most k layovers. Dijkstra fails here because a cheaper flight path may require too many stops.
Example 3 · Brute force: try every route with DFS, exponential time
public class Main { static int best;
static void dfs(int[][] flights, int city, int dst, int flightsLeft, int cost) { if (city == dst) { best = Math.min(best, cost); return; } if (flightsLeft == 0) return; for (int[] f : flights) { if (f[0] == city) dfs(flights, f[1], dst, flightsLeft - 1, cost + f[2]); } }
static int cheapest(int[][] flights, int src, int dst, int k) { best = Integer.MAX_VALUE; dfs(flights, src, dst, k + 1, 0); // k stops means at most k + 1 flights return best == Integer.MAX_VALUE ? -1 : best; }
public static void main(String[] args) { int[][] flights = {{0, 1, 100}, {1, 2, 100}, {0, 2, 500}, {2, 3, 200}, {1, 3, 600}}; System.out.println("With 1 stop: " + cheapest(flights, 0, 3, 1)); System.out.println("With 2 stops: " + cheapest(flights, 0, 3, 2)); }}With 1 stop: 700 With 2 stops: 400
What this code does
- The search follows every route of at most k + 1 flights and keeps the cheapest.
- The number of routes can grow like (flights per city) to the power k + 1.
- Bellman-Ford instead keeps one best cost per city per round, so it never repeats a route.
Example 4 · Optimal: Bellman-Ford with K + 1 rounds, O(K * E) time
import java.util.Arrays;
public class CheapestFlightsDemo { public static int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) { int INF = 1_000_000_000; int[] dist = new int[n]; Arrays.fill(dist, INF); dist[src] = 0;
for (int i = 0; i <= k; i++) { int[] temp = Arrays.copyOf(dist, n); for (int[] flight : flights) { int u = flight[0]; int v = flight[1]; int price = flight[2]; if (dist[u] != INF && dist[u] + price < temp[v]) { temp[v] = dist[u] + price; } } dist = temp; } return dist[dst] == INF ? -1 : dist[dst]; }
public static void main(String[] args) { int n = 4; int[][] flights = { {0, 1, 100}, {1, 2, 100}, {0, 2, 500}, {2, 3, 200}, {1, 3, 600} }; int cost0 = findCheapestPrice(n, flights, 0, 3, 1); int cost1 = findCheapestPrice(n, flights, 0, 3, 2); System.out.println("With 1 stop: " + cost0); System.out.println("With 2 stops: " + cost1); }}With 1 stop: 700 With 2 stops: 400
What this code does
- Runs exactly k + 1 relaxation passes, bounding the path to at most k intermediate stops.
- Clones the distance array so edges relaxed in round i do not cascade into round i + 1.
- Returns 700 for 1 stop (0->1->3) and 400 for 2 stops (0->1->2->3).
- Each round keeps one best cost per city, so the work is K + 1 passes over the flights instead of every possible route.
Bellman-Ford naturally solves this problem when restricted to exactly k + 1 rounds. Each iteration corresponds to paths containing exactly one more flight segment. To prevent multi-hop cascades in a single round, copy the distance array first. Only use distances computed in the previous round when relaxing edges. Trace three flights: S->A for 100, A->B for 100, and S->B for 500. With k = 0 stops, only direct flights are eligible, so dist[B] is 500. With k = 1 stop, round 2 allows path S->A->B with cost 200. Cloning the array guarantees that round 1 does not cascade S->A and A->B together.
Next step
Check your understanding
10 quick questions