Depth 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 Stack has been created and initialized to an empty state.
Procedure DepthFirstTraversal
{
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;
Push V onto the Stack ;
While ( the Stack is not empty )
{ /* begin while-loop */
Let X be the top element of the Stack ;
If ( X has an adjacent vertex N
with status(N) = WAITING )
Then
{
Process N;
Set status(N) to VISITED;
Push N onto the Stack;
/* If calculating a spanning tree
then here mark the edge between N and X */
}
Else Pop X from the Stack ;
} /* end while-loop */
} /* End Procedure VisitComponentOf */
Recursive Version of Procedure VisitComponentOf
Procedure VisitComponentOf(vertex V)
{ /* Begin Procedure VisitComponentOf */
Process V ;
Set status(V) to VISITED ;
For each N adjacent to V
If status(N) is WAITING
{
VisitComponentOf(N) ;
/* If calculating a spanning tree
then here mark the edge between N and X */
}
} /* 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 V". (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.