(Latest Revision: Tue Oct 31 22:28:41 PST 2000 ) graphDpthSrch

graphDpthSrch




ALGORITHM FOR A DEPTH-FIRST TRAVERSAL

       /* Traverse a graph, starting at vertex v. */
dfs (in v:Vertex)
{
  s.createStack() ;
  mark v as visited ;
  s.push(v) ;

/* LOOP INVARIANT: THERE IS PATH FROM VERTEX v AT THE BOTTOM
   OF THE STACK s TO THE VERTEX AT THE TOP OF s. */

  while ( !s.isEmpty() )
  {
          /* LOOK FOR AN UNVISITED NODE ADJACENT TO THE TOP NODE. */
    if   (no unvisited vertices are adjacent to the vertex on the
          top of the stack)

          s.pop() ; /* (BACKTRACK) */

    else  
       {
             /* SELECT AN UNVISITED VERTEX u ADJACENT TO THE
		VERTEX ON THE TOP OF THE STACK. */

          mark u as visited ;

          s.push(u) ;

       } /* end if-else */
  } /* end while */
} /* end dfs */