Bellman-Ford Algorithm

In short: The Bellman-Ford algorithm finds the shortest path from one start node to every other node in a weighted, directed graph, even when some edge weights are negative. It relaxes every edge V - 1 times, since a shortest path has at most V - 1 edges, and one extra pass detects any negative cycle reachable from the start. It runs in O(V·E) time and O(V) space.

Quick reference

The Bellman-Ford algorithm finds the shortest path from one starting node to every other node in a weighted, directed graph, even when some edges have negative weights. It goes through every edge V - 1 times (where V is the number of nodes), lowering a node's distance whenever an edge gives a cheaper way to reach it. Then one more pass tells you whether the graph has a negative cycle. It runs in O(V · E) time.

When to use it:

  • You need the shortest paths from one start node, and some edge weights are negative, so Dijkstra's algorithm can give the wrong answer.
  • You need to know whether the graph has a negative cycle: a loop whose weights add up to less than zero.
  • The problem limits how many edges a path can use, like "the cheapest flight with at most k stops."

How it works:

  1. Set the start node's distance to 0 and every other node's distance to infinity.
  2. V - 1 times: for every edge from u to v with weight w, if distance[u] + w is less than distance[v], lower distance[v] to distance[u] + w. Stop early if a whole pass changes nothing.
  3. Go through the edges one more time. If any edge can still lower a distance, there's a negative cycle you can reach from the start node.

Cost:

  • O(V · E) time, where E is the number of edges, and O(V) extra space for the distances.

How the Bellman-Ford Algorithm Works

The basic move is called relaxing an edge. Say we know a way to get to node u that costs distance[u], and there's an edge from u to v with weight w. Then we can get to v for distance[u] + w. If that's cheaper than the best way to v we've found so far, we lower distance[v].

Dijkstra's algorithm relaxes edges too, but it's picky about the order: it always works outward from the closest node it hasn't finished yet, and once a node is finished, it never looks at it again. Bellman-Ford doesn't try to be clever. It relaxes every edge, then does it again, and again, until nothing can improve:

distance[start] = 0 distance[every other node] = infinity repeat V - 1 times: for each edge (u, v) with weight w: if distance[u] + w < distance[v]: # relax the edge distance[v] = distance[u] + w if nothing changed in this pass: stop early for each edge (u, v) with weight w: # the extra check pass if distance[u] + w < distance[v]: report a negative cycle

Two things to notice:

  • The order of the edges doesn't matter for correctness. Any order works. A lucky order just finishes in fewer passes.
  • We can stop early. If a whole pass goes by without changing any distance, the next pass would see exactly the same distances and change nothing too. So we're done.

Bellman-Ford Example, Step by Step

Say node 0 is your bakery, and the other nodes are places your delivery van can drive to. Each edge is a one-way road, and its weight is what it costs to drive it. The road from node 2 to node 1 has a weight of −4 because it passes a customer who pays you to drop off a cake on the way, so driving it earns you more than it costs.

Here are the roads, in the order we'll relax them on every pass. (We picked an unlucky order on purpose, so we can see why one pass isn't enough.)

Edge Weight
1 → 3 3
2 → 1 −4
0 → 1 2
0 → 2 4
0 → 3 6

There are 4 nodes, so we'll do up to 4 - 1 = 3 passes, then one check pass:

Pass Edges that lowered a distance Node 0 Node 1 Node 2 Node 3
Start — 0 ∞ ∞ ∞
1 0 → 1 (∞ to 2), 0 → 2 (∞ to 4), 0 → 3 (∞ to 6) 0 2 4 6
2 1 → 3 (6 to 5), 2 → 1 (2 to 0) 0 0 4 5
3 1 → 3 (5 to 3) 0 0 4 3
Check None, so there's no negative cycle 0 0 4 3

Here's what happened:

  • Pass 1: the first two edges start at nodes 1 and 2, and we can't reach those yet (their distance is infinity), so they can't help. The last three edges leave the bakery and set nodes 1, 2, and 3 to 2, 4, and 6.
  • Pass 2: 1 → 3 gives node 3 a cheaper route: 2 + 3 = 5. Then 2 → 1 gives node 1 a cheaper route: 4 + (−4) = 0. But we already relaxed 1 → 3 earlier in this pass, using node 1's old distance of 2.
  • Pass 3: 1 → 3 now uses node 1's new distance: 0 + 3 = 3.

The final distances are 0, 0, 4, and 3. The cheapest way to node 3 is 0 → 2 → 1 → 3, which costs 4 − 4 + 3 = 3. That path has 3 edges, and with our unlucky order, each pass only pushed the right answer one edge further along it.

If we'd listed the edges in a luckier order (0 → 1, 0 → 2, 2 → 1, 1 → 3, 0 → 3), pass 1 would find every final distance, pass 2 would change nothing, and we'd stop early. Bellman-Ford can't count on a lucky order, so in the worst case it needs all V - 1 passes.

Why Dijkstra's algorithm gets this graph wrong

Dijkstra's algorithm, written the usual way, takes the closest unfinished node out of a priority queue and treats its distance as final. Here's what it does with the same roads:

Step Node taken out (now final) What happens Distances to nodes 0, 1, 2, 3
1 0 (cost 0) 0 → 1, 0 → 2, and 0 → 3 set nodes 1, 2, and 3 to 2, 4, and 6 0, 2, 4, 6
2 1 (cost 2) 1 → 3 lowers node 3 to 2 + 3 = 5 0, 2, 4, 5
3 2 (cost 4) 2 → 1 would lower node 1 to 4 + (−4) = 0, but node 1 is already final, so it's skipped 0, 2, 4, 5
4 3 (cost 5) No roads leave node 3 0, 2, 4, 5

Dijkstra's algorithm says it costs 2 to reach node 1 and 5 to reach node 3. The real answers are 0 and 3. It finalized node 1 before it found the cheaper route through node 2, which is exactly the mistake that "no negative weights" rules out: with only non-negative weights, a path that goes through a farther-away node can never come out cheaper.

Some Dijkstra implementations never mark nodes as final. They just push a node back into the priority queue whenever its distance drops. Those happen to get this graph right, but with negative weights they lose Dijkstra's speed guarantee, and if there's a negative cycle, they never stop.

Why V - 1 Passes Are Enough

A shortest path never needs to visit the same node twice. If it did, it would contain a loop. As long as no loop has a negative total weight, cutting the loop out gives a path that's at least as cheap. A path that doesn't repeat any nodes visits at most V nodes, so it has at most V - 1 edges.

Now look at what each pass guarantees. Take any node v and the edges along its shortest path from the start: start → a → b → … → v.

  • Pass 1 relaxes every edge, including start → a. So after pass 1, a has its final distance (if it didn't already).
  • Pass 2 relaxes a → b, starting from a's final distance. So after pass 2, b has its final distance.
  • And so on: after pass i, the node i edges along the path has its final distance.

The path has at most V - 1 edges, so after V - 1 passes, v has its final distance. That's true for every node, whatever order we relax the edges in.

This is dynamic programming. After pass i, each node's distance is at least as good as the cheapest path to it that uses at most i edges, and each pass builds those answers from the previous pass's answers:

best[i][v] = min(best[i - 1][v], best[i - 1][u] + w), over every edge u → v with weight w.

Updating one array of distances in place, as Bellman-Ford does, can only make the distances better sooner. That's why a lucky order can finish early.

Detecting Negative Cycles

A negative cycle is a loop whose weights add up to less than zero. In our delivery example, it'd be a loop of roads that pays you more than it costs to drive. You could drive it forever and make money every time around, so there's no cheapest route to anywhere you can reach from that loop: there's always a cheaper one that goes around the loop once more.

That's why Bellman-Ford does an extra pass. Let's add a road from node 3 to node 2 with a weight of −1. Now the loop 2 → 1 → 3 → 2 costs −4 + 3 + (−1) = −2.

Pass Edges that lowered a distance Node 0 Node 1 Node 2 Node 3
1 0 → 1, 0 → 2, 0 → 3 0 2 4 6
2 1 → 3 (6 to 5), 2 → 1 (2 to 0) 0 0 4 5
3 1 → 3 (5 to 3), 3 → 2 (4 to 2) 0 0 2 3
Check 2 → 1 would still lower node 1, from 0 to −2 Negative cycle!

Why does the check pass always catch a negative cycle? Suppose no edge on the loop could lower a distance. Then for each edge u → v on the loop, distance[v] <= distance[u] + w. Add those inequalities up all the way around the loop. Every node's distance shows up once on each side, so they cancel, and we're left with 0 ≤ the loop's total weight. That contradicts the loop being negative, so some edge on it can always still lower a distance.

Two things to keep in mind:

  • Bellman-Ford only finds negative cycles you can reach from the start node. To check the whole graph, start every node at a distance of 0 instead of infinity. (That's the same as adding a new start node with a 0-weight edge to every other node.)
  • A negative cycle doesn't ruin every distance. Only nodes you can reach from the cycle have no shortest path. To find them, collect every node whose distance can still drop in the check pass, then run a breadth-first search from those nodes. Everything it reaches has no shortest path. Every other node's distance is correct.

Bellman-Ford Algorithm Code

Here's Bellman-Ford with the early exit and the negative cycle check. Nodes are numbered 0 to V - 1, and the graph is just an array of edges, each with a starting node, an ending node, and a weight. This is the example from above:

import java.util.Arrays; private static final int UNREACHABLE = Integer.MAX_VALUE; // each edge is {fromNode, toNode, weight}, and nodes are numbered 0 to numNodes - 1 public static int[] bellmanFord(int numNodes, int[][] edges, int start) { // every node starts out unreachable, except the start node int[] distances = new int[numNodes]; Arrays.fill(distances, UNREACHABLE); distances[start] = 0; // a shortest path uses at most numNodes - 1 edges, // so numNodes - 1 passes over the edges are enough for (int pass = 0; pass < numNodes - 1; pass++) { boolean changed = false; for (int[] edge : edges) { int fromNode = edge[0], toNode = edge[1], weight = edge[2]; // skip edges out of nodes we can't reach yet: adding to // Integer.MAX_VALUE would overflow into a negative number if (distances[fromNode] == UNREACHABLE) { continue; } // relax the edge: is going through fromNode a cheaper way to get to toNode? if (distances[fromNode] + weight < distances[toNode]) { distances[toNode] = distances[fromNode] + weight; changed = true; } } // nothing improved in this pass, so nothing will in the next one either if (!changed) { break; } } // one more pass: if any edge can still improve a distance, // there's a negative cycle we can reach from start for (int[] edge : edges) { int fromNode = edge[0], toNode = edge[1], weight = edge[2]; if (distances[fromNode] != UNREACHABLE && distances[fromNode] + weight < distances[toNode]) { throw new IllegalArgumentException("Graph has a negative cycle reachable from the start node"); } } return distances; } // int[][] edges = {{1, 3, 3}, {2, 1, -4}, {0, 1, 2}, {0, 2, 4}, {0, 3, 6}}; // bellmanFord(4, edges, 0) returns [0, 0, 4, 3]

Some notes on the code:

  • Infinity. In Python and JavaScript, infinity plus a number is still infinity, so the comparison takes care of unreachable nodes. Java and C++ ints don't have an infinity, so we use the biggest int as a stand-in and skip edges out of nodes we haven't reached yet. Adding to it would overflow and wrap around to a big negative number.
  • Getting the path, not just its cost. Keep an array of previous nodes. Every time you lower distance[v] using the edge from u, set previous[v] = u. At the end, follow the previous nodes back from the destination to the start, then reverse the result.
  • Undirected graphs. Add each undirected edge in both directions. But watch out: an undirected edge with a negative weight is a negative cycle all by itself, since you can go back and forth across it forever.

Bellman-Ford Time and Space Complexity

Time: O(V · E). There are up to V - 1 passes plus the check pass, and each pass relaxes all E edges in O(1) time apiece. With the early exit, the best case is two passes, or O(E), when the first pass happens to find every final distance.

Space: O(V) extra, for the distances (and the previous nodes, if you track paths). The edges themselves are the input.

That's slower than Dijkstra's O((V + E) log V). On a dense graph, where E is close to V^2, Bellman-Ford takes O(V³) time. So only reach for it when you actually have negative weights or need to find negative cycles. For more on how to count steps like this, see our big O notation guide.

Bellman-Ford vs. Dijkstra vs. Floyd-Warshall

All three find shortest paths in weighted graphs. Here's how they compare (V is the number of nodes and E is the number of edges):

Dijkstra's algorithm Bellman-Ford Floyd-Warshall
Finds Shortest paths from one start node Shortest paths from one start node Shortest paths between every pair of nodes
Negative edge weights? No Yes Yes
Detects negative cycles? No Yes, if you can reach them from the start node Yes: some dist[i][i] ends up below 0
Time O((V + E) log V) with a binary heap O(V · E) O(V³)
Extra space O(V) O(V) O(V²)
Approach Greedy: finalize the closest unfinished node, using a priority queue Dynamic programming: relax every edge, V - 1 times Dynamic programming: allow one more node as a stop in between, V times
Typical use Maps, routing, and any graph where weights are never negative Graphs with negative weights; finding negative cycles (like a loop of currency trades that makes money); limits on the number of edges Small or dense graphs where you need the distance between every pair; checking which nodes can reach which

So which one should you use?

  • Every edge has the same weight (or no weight): a plain breadth-first search finds shortest paths in O(V + E).
  • No negative weights: Dijkstra's algorithm.
  • Some negative weights, one start node: Bellman-Ford.
  • No cycles at all (a DAG), even with negative weights: relax each node's outgoing edges in topological order. One pass is enough, so it takes O(V + E) time.
  • Distances between every pair of nodes in a small graph: the Floyd-Warshall algorithm.

You might also see the Shortest Path Faster Algorithm (SPFA). It's Bellman-Ford with a queue of nodes whose distance just dropped, so it only relaxes edges that might help. It's often faster in practice, but its worst case is still O(V · E).

Common Bellman-Ford Mistakes and Interview Tips

  • Adding to "infinity" in Java or C++. If infinity is Integer.MAX_VALUE, then infinity plus a positive weight overflows to a negative number, and infinity plus a negative weight looks like a real distance that's slightly less than infinity. Either way, unreachable nodes get fake distances, and you might even report a negative cycle that you can't reach. Skip edges out of nodes whose distance is still infinity.

  • Not doing enough passes. One pass is only enough if you get lucky with the edge order. You need V - 1 passes (or an early exit when a pass changes nothing).

  • Limits on the number of edges. For "the cheapest route with at most k edges," do k passes, but relax each pass using a copy of the distances from the previous pass. Otherwise one pass can chain several edges together. (With the lucky order in our example, pass 1 already found the 3-edge path 0 → 2 → 1 → 3.)

  • Expecting it to find every negative cycle. Starting from one node, it only finds the ones that node can reach. Start every distance at 0 to check the whole graph.

  • Using it when you don't need it. If no weights are negative, Dijkstra's algorithm is faster. Say why you're choosing Bellman-Ford: "some weights are negative" or "we need to detect negative cycles."

Practice

Our practice question Cake Delivery Route asks for the fastest route for a bakery's delivery van. Drive times are never negative, so it's a job for Dijkstra's algorithm, and one of its bonus questions asks what changes when some roads have negative costs. That's where Bellman-Ford comes in.

Frequently Asked Questions

What is the Bellman-Ford algorithm?

It's a single-source shortest path algorithm that works even when some edge weights are negative. It relaxes every edge V - 1 times, lowering a node's distance whenever an edge gives a cheaper way to reach it, then goes through the edges once more to check for negative cycles.

Why does Bellman-Ford relax the edges V - 1 times?

Without negative cycles, a shortest path never visits a node twice, so it has at most V - 1 edges. After pass i, the node i edges along any shortest path has its final distance, so after V - 1 passes every distance is final.

How does Bellman-Ford detect a negative cycle?

After the V - 1 passes, it goes through the edges one more time. If any edge can still lower a distance, there's a negative cycle reachable from the start node. To check the whole graph instead, start every node at a distance of 0 instead of infinity.

What is the time complexity of Bellman-Ford?

O(V·E), where V is the number of nodes and E is the number of edges: up to V - 1 passes plus a check pass, each relaxing every edge in O(1) time. It uses O(V) extra space, and stopping early when a pass changes nothing makes the best case O(E).

What's the difference between Bellman-Ford and Dijkstra's algorithm?

Both find shortest paths from one start node. Dijkstra's algorithm is faster, O((V + E) log V) with a binary heap, but it can give wrong answers when some edge weights are negative. Bellman-Ford takes O(V·E) time but handles negative weights and detects negative cycles.

Is Bellman-Ford dynamic programming?

Yes. After pass i, each node's distance is at least as good as the cheapest path to it that uses at most i edges, and each pass builds those answers from the previous pass's answers. Dijkstra's algorithm, by contrast, is greedy.

Reviewed by Stephen Cognetta, CEO of Aced. Last updated: December 4, 2026

. . .