Please see github.com/anusha-murali for all of my repositories.
The Bellman-Ford algorithm allows us to find the shortest paths with arbitrary edge weights. We decrease $d[v]$ only when the current value of $d[v]$ is greater than $d[u] + \text{length}(u,v)$. Whenever we updae $d[v]$, we also save its parent node.
def update (u,v):
if d[v] > d[u] + length(u,v):
d[v] = d[u] + length(u,v)
prev[v] = u # Remember the previous node
The algorithm maintains the distance of a vertex so that it is always a conservative overestimate; it will only update the a value when a suitable path is discovered to show that the overestimate can be lowered.
The following is the pseudocode for Bellman-Ford:
def bellman_ford(G, s):
for all v in V:
d[v] <- infty; pi[s] <- null
d[s] = 0
for i in range(n-1):
for (v, w) in E:
update(v, w)
return (d, pi)
Notes:
Example: Find the shortest path to all other nodes from node $A$.
We walk through the algorithm in steps as shown below:
(1) Initialize $d[]$ and $\pi[]$:
(2) First iteration: 1 hop from $A$
(3) Second iteration: 2 hops from $A$
(4) Third iteration: 3 hops from $A$
(5) Fourth iteration: 4 hops from $A$
Algorithm terminates!
What is a negative cycle? A negative-weight cycle is a cycle in a graph whose edges sum to a negative value.
Steps
update
$(u,v)$Run-time: Run-time is still $O(|V||E|)$.
Claim: If you run Bellman-Ford for $n$ rounds, there will be a change in $d[\cdot]$ iff graph has a negative cycle.
Proof:
Example: Check for negative cycle in the following graph.
The following diagram shows the shortest distances in red after the 4th iteration:
The following diagram shows the shortest distances in red on the 5th iteration:
The 5-hop walk $A \rightarrow C \rightarrow B \rightarrow D \rightarrow C \rightarrow B$ updates $d[B]$ again. Therefore, Bellman-Ford has detected a cycle in this graph!
Data Structures and Algorithms Table of Contents