5.1 Recursive Depth First Search

Algorithm 4 performs a depth-first search of G G rooted at r r . The counters d f n dfn and d e p t h depth are global. It relies upon the recursive procedure dfs. Algorithm 5 sketches the implementation of the dfs procedure.

Algorithm 4: Depth First Search
while next( V V ) f i n i s h e d \neq finished
   map( γ , v , u n v i s i t e d \gamma,v,unvisited )
d e p t h = d f n = 0 depth=dfn=0
dfs( r r )
Algorithm 5: Recursive Depth First Search
dfs( v v )
    d f n = d f n + 1 dfn=dfn+1
   map( γ , v , d f n \gamma,v,dfn )
   map( δ , v , d e p t h \delta,v,depth )
    d e p t h = d e p t h + 1 depth=depth+1
   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
         map( ρ , w , v \rho,w,v )
         dfs( w w )
    d e p t h = d e p t h - 1 depth=depth-1

Observe that Algorithm 5 produces three mappings as it performs the DFS: the depth first ordering γ \gamma , the vertex depth map δ \delta , and the predecessor map ρ \rho . These mappings provide useful information concerning the structure of the graph. However, only γ \gamma is actually required by the algorithm. It is initialized with all vertices marked as u n v i s i t e d unvisited and updated as each node is visited.

The time complexity of a depth-first search is linear in the size of G G , i.e.  O V + E O\left(|V|+|E|\right) . To achieve this linear time complexity, the implementation of the adjacency list is crucial. More specifically, some indication of the most recently visited neighbor (call it vertex w w ) must be maintained for each active vertex v v . This permits the scan of v v ’s adjacency list to resume at the point where it was suspended when the exploration of w w is finished. If you have to rescan the adjacency list of v v to pick up where you left off, linearity is lost.