Professional Documents
Culture Documents
Bfs
Bfs
L0
L1
L2
A
C
E
Breadth-First Search
D
F
Breadth-First Search
Breadth-first search
(BFS) is a general
technique for
traversing a graph
A BFS traversal of a
graph G
Breadth-First Search
BFS Algorithm
The algorithm uses a
mechanism for setting
and getting labels of
vertices and edges
Algorithm BFS(G)
Input graph G
Output labeling of the edges
and partition of the
vertices of G
for all u G.vertices()
setLabel(u, UNEXPLORED)
for all e G.edges()
setLabel(e, UNEXPLORED)
for all v G.vertices()
if getLabel(v) UNEXPLORED
BFS(G, v)
2004 Goodrich, Tamassia
Algorithm BFS(G, s)
L0 new empty sequence
L0.insertLast(s)
setLabel(s, VISITED)
i0
while Li.isEmpty()
Li 1 new empty sequence
for all v Li.elements()
for all e G.incidentEdges(v)
if getLabel(e) UNEXPLORED
w opposite(v,e)
if getLabel(w) UNEXPLORED
setLabel(e, DISCOVERY)
setLabel(w, VISITED)
Li 1.insertLast(w)
else
setLabel(e, CROSS)
i i 1
Breadth-First Search
Example
unexplored vertex
visited vertex
unexplored edge
discovery edge
cross edge
A
A
L0
L1
L0
L1
L0
C
E
C
E
L1
Breadth-First Search
D
F
C
E
D
F
Example (cont.)
L0
L1
L0
C
E
L0
L1
L0
C
E
L2
L2
L1
D
F
L1
C
E
Breadth-First Search
L2
C
E
D
F
Example (cont.)
L0
L1
L0
L1
L2
C
E
L1
L2
A
C
E
D
F
L2
L0
C
E
D
F
Breadth-First Search
Properties
Notation
Property 1
Property 2
The discovery edges labeled by
BFS(G, s) form a spanning tree
Ts of Gs
Property 3
For each vertex v in Li
L1
L0
Breadth-First Search
L2
C
E
D
F
Analysis
Setting/getting a vertex/edge label takes O(1) time
Each vertex is labeled twice
once as UNEXPLORED
once as VISITED
once as UNEXPLORED
once as DISCOVERY or CROSS
Recall that
v deg(v) 2m
Breadth-First Search
Applications
Using the template method pattern, we
can specialize the BFS traversal of a graph
G to solve the following problems in O(n
m) time
Breadth-First Search
DFS BFS
Spanning forest,
connected components,
paths, cycles
Shortest paths
Biconnected components
L0
A
B
C
E
D
F
DFS
2004 Goodrich, Tamassia
L1
L2
Breadth-First Search
C
E
BFS
D
F
10
w is an ancestor of v in
the tree of discovery
edges
L0
A
B
C
E
D
F
L1
L2
DFS
2004 Goodrich, Tamassia
A
C
E
D
F
BFS
Breadth-First Search
11