Title: Graph Traversals
1Graph Traversals
Visit vertices of a graph G to determine some
property
2Breadth-First Search
Find the shortest path from a source node s to
all other nodes.
Outputs
Idea Find nodes at distance 0, then at distance
1, then at distance 2,
3A BFS Example
b
s
e
c
g
f
a
d
4 b
s
e
c
g
f
a
d
Visualized as many simultaneous explorations
starting from s and spreading out independently.
5 b
s
e
c
g
f
a
d
Dashed edges were explored but had resulted in
the discovery of no new vertices.
L ? a, c?
1
6b
s
e
c
g
f
a
d
L ? a, c?
1
7The Finish
b
s
e
c
g
f
a
d
L ? a, c?
1
8Breadth-First Tree
3
0
2
3
1
2
1
2
visited vertices 1 tree edges
? 1 explored edges.
9The BFS Algorithm
BFS(G, s) for each v ? V(G) s do
d(v) ? ? // shortest distance from s
d(s) ? 0 // initialization
L ? ?s? T ? ? i ? 0 while L ? ?
do // all nodes at distance i from s
L ? ? ? for each u ? L do
for each v ? Adj(u) do if
d(v) ? then // not yet visited
d(v) ? d(u) 1
insert v into L T ? T
?? (u, v) i ? i 1
0
i
i1
i
i1
10Correctness
Lemma For each i, the set L includes all nodes
at distance i from s.
i
Proof By induction on the distance k from s.
Every node v at distance k1 from s must be
adjacent to a node u at distance k.
Corollary At the finish of BFS, d(v) is the
length of the shortest path
from s to v.
11Running Time
O(E) if G is represented using adjacency lists.
inserted vertices ? 1 scanned edges
? E 1.
Courtesy of Dr. Fernandez-Baca