This preview shows pages 1–2. Sign up to view the full content.
CE177 Schlag
Fall ’04
Handout # 2
Breadth First Search
The input is a simple graph. This algorithm traverses each component of the graph, numbering
vertices as they are encountered (
bfs[
u
]
) and saving for each vertex
u
the neighbor (if any) from
which it was ﬁrst discovered (
p[
u
]
). During the traversal a vertex can be one of three colors, white
as long as it is undiscovered, gray when it has been discovered but is still unexplored, and ﬁnally
black when it has been explored. A rooted tree is obtained for each component.
In the ﬁrst
forloop
all vertices are colored white and placed in the set
New
. In each iteration
of the outer
whileloop
a vertex is removed from
New
and placed in the empty queue
Q
. This
vertex is placed in
Roots
; it will serve as the root of a tree for the component currently being
explored.
The queue
Q
contains the vertices that have been discovered but not yet explored (gray vertices).
In each iteration of the inner
whileloop
an unexplored vertex is removed from
Q
and its edges
are explored. Any of its neighbors that are discovered for the ﬁrst time (are currently white) are
assigned
u
as their parent in the tree, and are added to
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
This is the end of the preview. Sign up
to
access the rest of the document.
 Spring '08
 Hari

Click to edit the document details