$ \def\compare{ {\mathrm{compare}} } \def\swap{ {\mathrm{swap}} } \def\sort{ {\mathrm{sort}} } \def\insert{ {\mathrm{insert}} } \def\true{ {\mathrm{true}} } \def\false{ {\mathrm{false}} } \def\BubbleSort{ {\mathrm{BubbleSort}} } \def\SelectionSort{ {\mathrm{SelectionSort}} } \def\Merge{ {\mathrm{Merge}} } \def\MergeSort{ {\mathrm{MergeSort}} } \def\QuickSort{ {\mathrm{QuickSort}} } \def\Split{ {\mathrm{Split}} } \def\Multiply{ {\mathrm{Multiply}} } \def\Add{ {\mathrm{Add}} } \def\cur{ {\mathrm{cur}} } \def\gets{ {\leftarrow} } $
Unweighted Single-Source Shortest Paths:
Solution: Breadth-first Search (BFS)
BFS(V, E, u):
intialize d[v] <- -1 for all v
d[u] <- 0
queue.add(u)
while queue is not empty do
v <- queue.remove()
for each neighbor w of v do
if d[w] = -1 then
d[w] <- d[v] + 1
queue.add(w)
return d
Correctness. Follows from interaction with queue: vertices added in order of increasing distance from $u$
BFS(V, E, u):
intialize d[v] <- -1 for all v
d[u] <- 0
queue.add(u)
while queue is not empty do
v <- queue.remove()
for each neighbor w of v do
if d[w] = -1 then
d[w] <- d[v] + 1
queue.add(w)
return d
Definition. A weighted graph is a graph $G(V, E)$ where each edge $e \in E$ is additionally assigned a (real valued) weight $w(e)$.
Examples.
$G = (V, E)$ a graph, $w$ weights
$P = v_0 e_1 v_1 e_2 v_2 \cdots e_k v_k$ a path
The (weighted) length of $P$ is
\[w(P) = w(e_1) + w(e_2) + \cdots + w(e_k)\]Given weights $w$, define $d_w(u, v)$ to be minimum (weighted) length of any path $P$ from $u$ to $v$.
What is $d_w(1, 3)$? What about $d_w(1, 5)$?
Input.
Output.
A map $d: V \to \mathbf{R}$ such that $d[v] = d_w(u, v)$ is the graph distance from $u$ to $v$
Does BFS compute weighted distances from $u$?
Does this work?
BFS succeeds on unweighted graphs because closer vertices are processed before farther vertices
Could we get similar behavior for weighted distances?
must ensure: vertices processed in order of weighted distance from $u$
how can we do this?
Idea. Process elements in order of weighted distance from $u$
Claim. For every vertex $v \in S$, $d[v]$ stores the correct (weighted) distance $d_w(u, v)$.
Claim. For every vertex $v \in S$, $d[v]$ stores the correct (weighted) distance $d_w(u, v)$.
Proof. Use induction on size of $S$. Set $k = $ size of $S$.
Base case $k = 1$. Only $u$ is added to $S$. Set $d[u] \gets 0$, which is correct answer.
Inductive hypothesis. When $S$ contains $k$ elements, $d[v]$ is correct for all vertices $v \in S$.
Consider next iteration of outer loop:
Must show: $d[x] = d_w(u, x)$; argue by contradiction
Must show: $d[x] = d_w(u, x)$; argue by contradiction
Conclusion. $d[x] = d_w(u, x)$, as claimed.