codezoned / ScriptsDump

The biggest dump of scripts ever!
http://www.codezoned.com/
143 stars 173 forks source link

BELLMAN FORD #277

Closed Shivam20233 closed 2 years ago

Shivam20233 commented 2 years ago

Bellman-Ford's single source shortest path algorithm. The algorithm calculates the shortest paths in a bottom-up manner. It first calculates the shortest distances which have at most one edge in the path. Then, it calculates the shortest paths with at-most 2 edges, and so on. After the i-th iteration of the outer loop, the shortest paths with at most i edges are calculated. There can be maximum |V| – 1 edges in any simple path, that is why the outer loop runs |v| – 1 times. The idea is, assuming that there is no negative weight cycle if we have calculated shortest paths with at most i edges, then an iteration over all edges guarantees to give the shortest path with at-most (i+1) edges.