...

/

Challenge: Bellmann-Ford

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 (u,v)(u,v) means checking whether

d(u)+w(u,v)<d(v),d(u) + w(u, v) < d(v),

in which case we can update the tentative distance d(v)d(v).

To run Bellmann-Ford from a starting node uu, we

  1. Initialize d(u)=0d(u) = 0 and d(v)=d(v) = \infty for vuv \neq u
...