Video in progress
A graph has edges with negative weights. How do you find the shortest path, and how do you detect a negative cycle?
Dijkstra doesn't work here, because it treats a node pulled from the queue as final. Bellman-Ford relaxes all the edges V−1 times, O(V·E). If some distance still decreases on the V-th pass, there is a negative cycle reachable from the source.
📖 Answer
Why V−1? If there is no cycle, the shortest path has at most V−1 edges. Each pass "fixes" at least one more edge of that path.
record Edge(int from, int to, long w) {}
static long[] bellmanFord(int n, List<Edge> edges, int src) {
final long INF = Long.MAX_VALUE / 4; // so that addition doesn't overflow
long[] dist = new long[n];
Arrays.fill(dist, INF);
dist[src] = 0;
for (int i = 0; i < n - 1; i++) {
boolean changed = false;
for (Edge e : edges) {
if (dist[e.from()] != INF && dist[e.from()] + e.w() < dist[e.to()]) {
dist[e.to()] = dist[e.from()] + e.w();
changed = true;
}
}
if (!changed) break; // early exit — helps a lot in practice
}
for (Edge e : edges) {
if (dist[e.from()] != INF && dist[e.from()] + e.w() < dist[e.to()]) {
throw new IllegalStateException("manfiy sikl bor");
}
}
return dist;
}
The dist[e.from()] != INF check isn't for nothing: a negative edge leaving an unreachable node would write "INF − 5" as a new distance.
If there is a negative cycle, the very notion of a "shortest path" doesn't exist: you can go around the cycle and lower the distance as much as you like. To find which nodes are affected, you run a BFS from the nodes that changed on the V-th pass and mark them -∞.
Where it shows up: currency arbitrage. If you turn exchange rates into weights of -log(rate), a cycle whose product is greater than 1 becomes a negative cycle.
Variants: SPFA processes only the changed nodes using a queue, which is faster on average, but the worst case is still O(V·E). If you need all pairs and V is a few hundred, use Floyd-Warshall, O(V³). On a large sparse graph, for all pairs, Johnson's algorithm reweights the edges once with Bellman-Ford and then runs Dijkstra from every node.
Sign up to mark studied questions and save your progress.