Bellman ford algorithm
Pattern: Shortest paths
Relax every edge n - 1 times: after round i, every shortest path that uses at most i edges is found. If any edge can still be relaxed after that, a negative cycle is reachable. Works with negative weights, unlike Dijkstra.
The problem
Given a directed weighted graph (weights may be negative) and a source, return the shortest distance to every vertex,
using 100000000 for vertices that cannot be reached, as GFG does. If a negative cycle is reachable from the source, return
[-1]. Vertices are numbered from 0 and each edge is [u, v, weight].
Think first
- How many edges can a shortest path use at most?
- What does one round of relaxing all edges achieve?
- How do you spot a negative cycle?
Hints
Brute force, and why it fails
Try every path: exponential (and infinite with a negative cycle).
The key insight
n - 1 rounds are enough for every simple path, so any later improvement must come from a cycle of negative weight.
Dry run
| dist | - - 0 |
|---|
Edges 0→1 (5), 1→0 (3), 1→2 (-1), 2→0 (1); source 2. dist[2] = 0.
The plan
dist[src] = 0
repeat n - 1 times: for (u, v, w): if dist[u] known and dist[u] + w < dist[v]: update
if any edge still relaxes: [-1]
Complexity
- Time
O(V × E)- Space
O(V)
n - 1 rounds over every edge.
Edge cases
- Unreachable vertices: 100000000.
- A negative cycle not reachable from the source: ignored.
- A single vertex.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<Integer> bellmanFord(int n, int[][] edges, int src) {
final int UNREACHED = 100000000; // this guide's "no path" value, as on GFG
int[] dist = new int[n];
Arrays.fill(dist, UNREACHED);
dist[src] = 0;
for (int round = 0; round < n - 1; round++) // n - 1 rounds: enough for any path without a repeated vertex
for (int[] e : edges)
if (dist[e[0]] != UNREACHED && dist[e[0]] + e[2] < dist[e[1]]) dist[e[1]] = dist[e[0]] + e[2];
for (int[] e : edges) // still improving after that: a negative cycle
if (dist[e[0]] != UNREACHED && dist[e[0]] + e[2] < dist[e[1]]) return Arrays.asList(-1);
List<Integer> out = new ArrayList<>();
for (int d : dist) out.add(d);
return out;
}
}C++
class Solution {
public:
vector<int> bellmanFord(int n, vector<vector<int>>& edges, int src) {
const int UNREACHED = 100000000; // this guide's "no path" value, as on GFG
vector<int> dist(n, UNREACHED);
dist[src] = 0;
for (int round = 0; round < n - 1; round++) // n - 1 rounds: enough for any path without a repeated vertex
for (const vector<int>& e : edges)
if (dist[e[0]] != UNREACHED && dist[e[0]] + e[2] < dist[e[1]]) dist[e[1]] = dist[e[0]] + e[2];
for (const vector<int>& e : edges) // still improving after that: a negative cycle
if (dist[e[0]] != UNREACHED && dist[e[0]] + e[2] < dist[e[1]]) return vector<int>{-1};
return dist;
}
};Python
class Solution:
def bellmanFord(self, n: int, edges: list[list[int]], src: int) -> list[int]:
UNREACHED = 100000000 # this guide's "no path" value, as on GFG
dist = [UNREACHED] * n
dist[src] = 0
for _ in range(n - 1): # n - 1 rounds: enough for any path without a repeated vertex
for u, v, w in edges:
if dist[u] != UNREACHED and dist[u] + w < dist[v]:
dist[v] = dist[u] + w
for u, v, w in edges: # still improving after that: a negative cycle
if dist[u] != UNREACHED and dist[u] + w < dist[v]:
return [-1]
return distCommon mistakes
- Relaxing from unreachable vertices.
- Running only n - 2 rounds.