Skip to content
Snippets Groups Projects
Commit 32205ef3 authored by Wolfgang Mulzer's avatar Wolfgang Mulzer
Browse files

Unweighted shortest paths.

parent dbb0b02d
No related branches found
No related tags found
No related merge requests found
......@@ -103,4 +103,50 @@ on a shortest path from $s$ to $v$. The, we can proceed recursively.
After this discussion, it is straightforward to extend BFS in order to solve
the SSSP-problem from $s$. With each vertex $v \in V$, we store two additional
properties: the \emph{distance} $v.\texttt{d}$ from $s$ to $v$, and the \emph{predecessor}
$v.\texttt{pred}$ of $v$
$v.\texttt{pred}$ of $v$. The distance and the predecessor are set as soon as a vertex
is encountered for the first time by the BFS.
\begin{verbatim}
Q <- new Queue
for v in vertices() do
v.found <- false
// NEW: Initially, the distances
// from s are infinite and the predecessor
// does not exist (we have not yet found a
// path from s to v)
v.d <- INFTY
v.pred <- NULL
// we have seen s, and the distance from s to
// itself is 0
s.found <- true
s.d <- 0
Q.enqueue(s)
while not Q.isEmpty() do
v <- Q.dequeue()
for w in v.neighbors() do
if not w.found then
w.found <- true
// NEW: Update the distance
// and the predecessor
w.d <- v.d + 1
w.pred <- v
Q.enqueue(w)
\end{verbatim}
\textbf{TODO:} Add example
As before, the running time of the modified version of BFS is $O(|V| + |E|)$, if the graph
is given as an adjacency list representation.
One can show that BFS solves the SSSP-problem in unweighted graphs: when the BFS-algorithm
terminates, for every $v \in V$, we have that (i) $v.\texttt{d} = d_G(s, v)$ (the distances
have been computed correctly); and (ii) $v.\texttt{pred}$ is the predecessor of $v$ on a shortest
path from $s$ to $v$ (if $v$ is reachable from $s$). If we draw all the $v.\texttt{pred}$-pointers
in $G$, we obtain a rooted tree with root $s$ that encodes all the shortest paths in $G$. This
tree is called a \emph{shortest path tree} for $s$ in $G$.
We will not do the
correctness proof here. Instead, in the next chapter, we look at at Dijkstra's algorithm, a generalization
of BFS for graphs with nonnegative edge weights. We will prove that Dijkstra's algorithm is
correct. This also implies the correctness of BFS.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment