5.2 Non-recursive Depth First Search

Since the procedure described in Section 5.1 has a depth of recursion of V |V| in the worst case, Algorithm 5 may have unacceptable execution characteristics (such as stack overflow) for large graphs. Algorithm 6 removes the recursion from the dfs function.

Algorithm 6: Depth First Search With Recursion Removed
dfs( r r )
   visit( r , n o p a r e n t r,noparent )
    v = r v=r
   next edge
   for all vertices w w adjacent to v v
      if evaluate( γ , w \gamma,w ) is u n v i s i t e d unvisited
          d e p t h = d e p t h + 1 depth=depth+1
         visit( w , v w,v )
          v = w v=w
   goto next edge
   if  v r v\neq r
       v = v= evaluate( ρ , v \rho,v )
       d e p t h = d e p t h - 1 depth=depth-1
      goto next edge

The vertex visitation procedure visit is straightforward and is specified in Algorithm 7.

Algorithm 7: Non-recursive DFS Vertex Visitation
visit( v , p r e d e c e s s o r v,predecessor )
   map( δ , v , d e p t h \delta,v,depth )
   map( ρ , v , p r e d e c e s s o r \rho,v,predecessor )
    d f n = d f n + 1 dfn=dfn+1
   map( γ , v , d f n \gamma,v,dfn )

Observe that vertex visitation (Algorithm 7) generates the three mappings ( γ \gamma , δ \delta , and ρ \rho ) that were produced by the recursive procedure. Note that the predecessor mapping ρ \rho is required by the unwound dfs procedure. It was not required by the recursive implementation since equivalent information is implicitly retained on the stack during recursion.

The computational complexity of this unwound procedure is similar to that of the recursive implementation.

When implementing non-recursive depth first search, don’t forget that the dfs function of Algorithm 6 is imbedded in the overall procedure defined by Algorithm 4.

See Sections and 5.1 for more information on these issues.