Challenge: Bellmann-Ford
Implement the Bellmann-Ford algorithm to solve SSSP problems in graphs with negative edge weights.
In this Challenge Lesson, we’ll implement the Bellmann-Ford algorithm, an alternative algorithm for the SSSP. While it runs slower than Dijkstra, it is able to correctly handle graphs with negative edge weights as long as there are no negative cycles.
The Bellmann-Ford algorithm
The Bellmann-Ford algorithm computes distances by repeatedly relaxing all edges of the graphs. Recall that relaxing an edge means checking whether
in which case we can update the tentative distance .
To run Bellmann-Ford from a starting node , we
- Initialize and for .
- Try to relax each edge of the graph.
- Repeat step (2) until the distance estimates do not change anymore.
Finally, the value of corresponds to the distance of node from node . As usual, we can also keep track of predecessor nodes when relaxing edges to construct the shortest paths themselves.
Example execution
Let’s run Bellmann-Ford on this small example graph, starting from node :
Get hands-on with 1400+ tech skills courses.