AlgoTales · Roadmap

Bellman-Ford

Advanced · 11 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Bellman-Ford finds cheapest routes even when some links have negative costs, such as a discount or a refund, and it can also tell you when a loop keeps making things cheaper forever. It repeatedly relaxes every link until nothing improves.

Practical use cases

  • Web app: Currency exchange loop alert. A wallet or forex dashboard lists exchange rates between currencies. Turning rates into costs and running Bellman-Ford can reveal a loop of conversions that ends with more money than you started with, which is either a chance or a data error. The app flags it so rates can be fixed.
  • Web app: Cheapest price with coupons. A checkout engine chains offers: bank cashback, store credit, wallet coins. Some steps lower the price, which are negative costs. Bellman-Ford finds the cheapest sequence and warns if rules create a loop that reduces the price endlessly, a bug that would lose money.
  • Web app: Checking schedule constraints. A planning tool has rules like "task B starts at least 2 days after A" and "C must finish no later than 5 days after A". These form a graph, and a negative loop means the rules contradict each other, so the tool shows "impossible schedule".
  • System: Distance-vector routing. Older network routing protocols let each router share its best known costs with neighbours round after round, which is exactly this algorithm spread over machines. The trick is that every round lets the best-known cost travel one more link, so after enough rounds an extra improvement can only mean a never-ending loop of gains.

The story: The Discount Road

Raju found a road in the city where the toll collector paid you money. "Cashback on this lane!" The road cost minus 3 rupees. Kabir tried Dijkstra, locking the cheapest places first, but it gave wrong answers. A negative road breaks the promise that "once locked, never cheaper".

Mira said, "Let us stop being clever and be patient instead." She wrote all the roads in one list. Then, again and again, she went down the whole list and asked of every road: "Does this road give a cheaper cost to where it points?" If yes, update.

After the first pass, the news of the best route had travelled at least one road. After the second, at least two roads. After as many passes as there are roads in the longest sensible route, nothing could improve. If something still improved at the end, a loop of net negative cost existed, and a trip could be made cheaper forever.

That slow but safe method is the Bellman-Ford algorithm. It handles negative edges and warns you about negative cycles.

How to spot this problem, and where you need it

You want cheapest routes, but some steps give money back or reduce cost, so the usual greedy route finder can give wrong answers, and you also need to catch impossible loops.

Signs you need it

  • Links can have negative numbers such as discounts, refunds, gains or time offsets.
  • The problem asks "is there a way to keep gaining forever?" or "do these rules contradict each other?".
  • Dijkstra gives a wrong or odd result on your data, and you notice there is a negative value.

Where to use it in a project

  • Currency or points conversion features where a loop of trades could create free money by mistake.
  • Rule or constraint checkers for schedules, pricing and workflows where steps can shift earlier or later.

The solution

Set the start cost to 0 and all others to infinity. Repeat as many rounds as there are nodes minus one: in each round, go through every link, and if cost of start plus link cost is lower than the end's cost, update the end. After those rounds, do one more round; if anything still improves, a negative loop exists and there is no finite best answer. Otherwise the costs are final.

Payoff: Before: an arbitrage loop of three currencies silently drains money in production. After: a nightly check spots the loop and flags it before anyone profits.

Explain it like I am 8

Imagine whispering the best price to your friends down a line. Each round, everyone checks the price whispered to them and passes a better one if they know it. After enough rounds, even the last friend in the line has the best price. And if prices still drop after the last round, there is a magic money loop!

How it works, step by step

  1. Set all distances to infinity except the start (0). Keep all edges in a simple list.
  2. Do V − 1 rounds. In each round go through every edge (u → v, w) and relax it: if dist[u] + w < dist[v], update.
  3. Stop early if a whole round changes nothing.
  4. Do one extra round. If an edge can still be relaxed, there is a negative cycle reachable from the start.
  5. Skip edges from unreachable (infinite) vertices so you do not add numbers to infinity.

The code in four languages

PHP

<?php
// edges: list of [from, to, weight] (directed). Returns distances, or null on a negative cycle.
function bellmanFord(array $nodes, array $edges, string $src): ?array {
    $dist = array_fill_keys($nodes, INF);
    $dist[$src] = 0;
    for ($round = 1; $round < count($nodes); $round++) {     // V - 1 rounds
        $changed = false;
        foreach ($edges as [$u, $v, $w]) {
            if ($dist[$u] !== INF && $dist[$u] + $w < $dist[$v]) {
                $dist[$v] = $dist[$u] + $w;                  // relax
                $changed = true;
            }
        }
        if (!$changed) break;                                // settled early
    }
    foreach ($edges as [$u, $v, $w]) {                       // one extra look
        if ($dist[$u] !== INF && $dist[$u] + $w < $dist[$v]) return null;   // negative cycle
    }
    return $dist;
}

$nodes = ['S', 'A', 'B', 'C'];
$edges = [['S','A',4], ['A','C',2], ['B','A',-3], ['S','B',5], ['B','C',6]];
foreach (bellmanFord($nodes, $edges, 'S') as $n => $d) echo "$n: $d\n";

$bad = [['S','A',1], ['A','B',-2], ['B','A',-2]];             // A <-> B loop costs -4 per lap
echo bellmanFord(['S','A','B'], $bad, 'S') === null ? "negative cycle found\n" : "ok\n";

JavaScript

// edges: list of [from, to, weight] (directed). Returns distances, or null on a negative cycle.
function bellmanFord(nodes, edges, src) {
  const dist = {};
  for (const n of nodes) dist[n] = Infinity;
  dist[src] = 0;
  for (let round = 1; round < nodes.length; round++) {      // V - 1 rounds
    let changed = false;
    for (const [u, v, w] of edges) {
      if (dist[u] !== Infinity && dist[u] + w < dist[v]) {
        dist[v] = dist[u] + w;                              // relax
        changed = true;
      }
    }
    if (!changed) break;                                    // settled early
  }
  for (const [u, v, w] of edges) {                          // one extra look
    if (dist[u] !== Infinity && dist[u] + w < dist[v]) return null;   // negative cycle
  }
  return dist;
}

const nodes = ['S', 'A', 'B', 'C'];
const edges = [['S','A',4], ['A','C',2], ['B','A',-3], ['S','B',5], ['B','C',6]];
const res = bellmanFord(nodes, edges, 'S');
for (const n of nodes) console.log(n + ': ' + res[n]);

const bad = [['S','A',1], ['A','B',-2], ['B','A',-2]];      // A <-> B loop costs -4 per lap
console.log(bellmanFord(['S','A','B'], bad, 'S') === null ? 'negative cycle found' : 'ok');

Java

import java.util.*;

public class Main {
    static final int INF = Integer.MAX_VALUE;

    // edges: list of {from, to, weight} (directed). Returns distances, or null on a negative cycle.
    static Map<String, Integer> bellmanFord(List<String> nodes, List<Object[]> edges, String src) {
        Map<String, Integer> dist = new LinkedHashMap<>();
        for (String n : nodes) dist.put(n, INF);
        dist.put(src, 0);
        for (int round = 1; round < nodes.size(); round++) {      // V - 1 rounds
            boolean changed = false;
            for (Object[] e : edges) {
                String u = (String) e[0], v = (String) e[1];
                int w = (int) e[2];
                if (dist.get(u) != INF && dist.get(u) + w < dist.get(v)) {
                    dist.put(v, dist.get(u) + w);                 // relax
                    changed = true;
                }
            }
            if (!changed) break;                                  // settled early
        }
        for (Object[] e : edges) {                                // one extra look
            String u = (String) e[0], v = (String) e[1];
            int w = (int) e[2];
            if (dist.get(u) != INF && dist.get(u) + w < dist.get(v)) return null;   // negative cycle
        }
        return dist;
    }

    public static void main(String[] args) {
        List<String> nodes = List.of("S", "A", "B", "C");
        List<Object[]> edges = List.of(new Object[]{"S", "A", 4}, new Object[]{"A", "C", 2},
            new Object[]{"B", "A", -3}, new Object[]{"S", "B", 5}, new Object[]{"B", "C", 6});
        for (var e : bellmanFord(nodes, edges, "S").entrySet()) System.out.println(e.getKey() + ": " + e.getValue());

        // A <-> B loop costs -4 per lap
        List<Object[]> bad = List.of(new Object[]{"S", "A", 1}, new Object[]{"A", "B", -2}, new Object[]{"B", "A", -2});
        System.out.println(bellmanFord(List.of("S", "A", "B"), bad, "S") == null ? "negative cycle found" : "ok");
    }
}

Go

package main

import (
	"fmt"
	"math"
)

type Edge struct {
	from, to string
	weight   int
}

// bellmanFord takes directed edges. It returns the distances, or ok=false on a negative cycle.
func bellmanFord(nodes []string, edges []Edge, src string) (dist map[string]int, ok bool) {
	dist = map[string]int{}
	for _, n := range nodes {
		dist[n] = math.MaxInt
	}
	dist[src] = 0
	for round := 1; round < len(nodes); round++ { // V - 1 rounds
		changed := false
		for _, e := range edges {
			if dist[e.from] != math.MaxInt && dist[e.from]+e.weight < dist[e.to] {
				dist[e.to] = dist[e.from] + e.weight // relax
				changed = true
			}
		}
		if !changed {
			break // settled early
		}
	}
	for _, e := range edges { // one extra look
		if dist[e.from] != math.MaxInt && dist[e.from]+e.weight < dist[e.to] {
			return nil, false // negative cycle
		}
	}
	return dist, true
}

func main() {
	nodes := []string{"S", "A", "B", "C"}
	edges := []Edge{{"S", "A", 4}, {"A", "C", 2}, {"B", "A", -3}, {"S", "B", 5}, {"B", "C", 6}}
	dist, _ := bellmanFord(nodes, edges, "S")
	for _, n := range nodes {
		fmt.Printf("%s: %d\n", n, dist[n])
	}

	// A <-> B loop costs -4 per lap
	bad := []Edge{{"S", "A", 1}, {"A", "B", -2}, {"B", "A", -2}}
	if _, ok := bellmanFord([]string{"S", "A", "B"}, bad, "S"); !ok {
		fmt.Println("negative cycle found")
	} else {
		fmt.Println("ok")
	}
}

Time: O(V × E) · Extra space: O(V). V − 1 rounds, each looking at all E edges. Slower than Dijkstra, but it accepts negative weights.

Watch out for

  • Adding to infinity. Skip edges whose start is still unreachable.
  • Forgetting the extra round, so negative cycles slip through silently.
  • Using it on an undirected graph with a negative edge. That edge alone is already a negative cycle (go back and forth).

Quick check

  1. Why V − 1 rounds?
    • It is a lucky number
    • Because the heap has V − 1 levels
    • A shortest path has at most V − 1 edges, and each round extends the news by one edge
  2. After V − 1 rounds, one more round still improves a distance. This means…
    • A negative cycle is reachable
    • A bug in the code
    • The graph is disconnected
  3. Bellman-Ford vs Dijkstra: which is true?
    • Dijkstra is slower but handles negatives
    • Bellman-Ford is slower but handles negatives
    • They cost the same