5 DP Bellman Ford Algorithm
An algorithm that works on graphs with negative weights.
From Djikstra's, we could possibly add a constant to all edges to make them all positive. However, if the shortest path (by weight) uses many edges, then the weight would have been increased for the entire path.
Negative weight graphs with cycles could cause a cycle and endlessly loop to decrease weight.
How it works¶
Build paths backward from a given node
This algorithm may run for
Recursive Function¶
Cases:
- The shortest
This function will end up being
It will be
Improving Space/Time Complexity¶
Improving Space Complexity
We don't need to store every single column to make this work, just the
This means we only need to store:
- the adjacency list of each node (in order to determine the in and out neighbours for each node) which is
Therefore, space complexity is reduced to
Improving Time Complexity
We don't need to check
We will only compare up to
Improvement: Push values ahead¶
- Notice that at each step of the algorithm we perform a fetch action to retrieve
or . - If we can instead push these values ahead each time, we can skip the nodes whose values won’t change.
- Initially when
only has a finite value - it is only reachable from itself. This means all paths using 1 edge must be of the form . - So the iteration when
, need only check those vertices such that , i.e., (u, t).
Basically, if we know a node
takes less than edges to get to the goal node , then we can just push it's weight to the next column for edges. In a subsequent iteration, if we find that we can reach taking a path from , then we flag it as something we updated and have to check in a future iteration, and update it's optimal weight.
Negative Cycles¶
Since Bellman Ford works for graphs with negative edge weights, what if there exists some negative cycle?
Reasonably, that implies we could have a path longer than the number of nodes
All we need to do is check that
Logically, this just means that if the shortest/least weight path from
to contains more than edges, the weight will not decrease. If it does, then we have found a negative weight cycle somewhere.
Claim: There is no negative cycle on a path to
Proof that the Bellman Ford has no cycles¶
Need to prove the iff
The version two of the proof for the forward direction
Reverse/Backward Direction of the IFF