$ \def\opt{ {\mathrm{opt}} } $
Adjacency List
Input:
Output:
Question. What if edge weights can be negative?
Question 1. Why can Dijkstra fail when edge weights can be negative?
Question 2. Why might shortest paths not exist when edge weights can be negative?
Assume. $G$ does not contain any negative weight cycles.
Claim. $G$ a graph with $n$ vertices, $u, v$ vertices in $G$. If $G$ does not contain negative weight cycles, then the shortest (weighted) path from $u$ to $v$ contains at most $n-1$ edges.
Why?
Suppose shortest path from $u$ to $x$ contains $j$ hops.
Idea. For each vertex $v$ and each $j = 1, 2, \ldots, n-1$ compute $d_j(u, v) = $ length of shortest path from $u$ to $v$ with at most $j$ hops.
Question 1. How to initialize $d_0(u, v)$?
Question 2. Given $d_j(u, v)$ for all v, how to find $d_{j+1}(u, v)$?
Bellman-Ford(V, E, w, u)
d <- 2d array [0..n-1, 1..n]
for v = 1 to n do d[0, v] <- infinity
d[0, u] <- 0
for j = 1 to n-1 do
for each vertex v in V set d[j, v] <- d[j-1,v]
for each vertex v in V
for each neighbor x of v
d[j, x] <- Min(d[j, x], d[j-1, v] + w[v, x])
return d[n-1]
Running time?
Claim. For all $j = 0, 1, \ldots, n-1$ and for all vertices $v$, $d[j, v]$ stores length of shortest path from $u$ to $v$ with $j$ or fewer hops. I.e., $d[j, v] = d_j(v)$
Proof. Induction on $j$.
Base case, $j = 0$.
If $G$ has no negative weight cycles, then Bellman-Ford solves single source shortest paths in $O(m n)$ time.
Running times:
Why pick Bellman-Ford over Dijkstra?
Bellman-Ford(V, E, w, u)
d <- 2d array [0..n-1, 1..n]
for v = 1 to n do d[0, v] <- infinity
d[0, u] <- 0
for j = 1 to n-1 do
for each vertex v in V set d[j, v] <- d[j-1,v]
for each vertex v in V
for each neighbor x of v
d[j, x] <- Min(d[j, x], d[j-1, v] + w[v, x])
return d[n-1]
Modeling the network:
Question 1. How much material can the USSR transport to Western Europe per unit time?
Question 2. What is the cheapest way to disrupt flow of material?
A new interpretation of directed graphs:
Question. How much fluid be routed from $s$ to $t$ per unit time?