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