Breadth First Traversal of a Graph
Set-Up:
- Each vertex of the graph has a status variable
which has one of two values: {WAITING, VISITED}
- A Queue has been created and initialized to an empty state.
Procedure BreadthFirstTraversal
{
Set the status of each vertex to WAITING ;
For each vertex V in the graph
If status(V) is WAITING
Then VisitComponentOf(V) ;
}
Iterative Version of Procedure VisitComponentOf
Procedure VisitComponentOf(vertex V)
{ /* Begin Procedure VisitComponentOf */
Process V ;
Set status(V) to VISITED;
Place V in the Queue ;
While ( the Queue is not empty )
{ /* begin while-loop */
Let X be the front element of the Queue;
Remove X from the Queue;
For each N adjacent to X with status(N) = WAITING
{
Process N;
Set status(N) to VISITED;
Place N in the Queue;
/* If calculating a spanning tree
then here mark the edge between N and X */
}
} /* end while-loop */
} /* End Procedure VisitComponentOf */
Note: The algorithms do not completely determine the
traversal order (the order in which the status of the
vertices will be set to VISITED). This is because the algorithms
do not specify in what order the vertices will be examined when
implementing a phrase like "For each N adjacent to X". (In test
situations, the student should assume that traversal begins at
the "Start Vertex" and that the adjacent vertices should be
examined in ascending key order.