Bellman-Ford Algorithm

Finds shortest paths from a source node, handling negative edge weights and detecting negative cycles.

42233115-52
S: Inf
A: Inf
B: Inf
C: Inf
D: Inf
E: Inf
Status: Click Run to Start
Speed
1function bellmanFord(edges, start):
2 dist[start] = 0, others = Inf
3
4 for i from 1 to V-1:
5 for each edge (u, v) with weight w:
6 if dist[u] + w < dist[v]:
7 dist[v] = dist[u] + w
8
9 // Check negative cycle
10 for each edge (u, v) with weight w:
11 if dist[u] + w < dist[v]:
12 error "Negative Cycle"

Unlike Dijkstra's, Bellman-Ford relaxes all edges |V|-1 times, allowing it to handle negative weights correctly.