5.1 Recursive Depth First Search
Algorithm 4 performs a depth-first search of rooted at . The counters and are global. It relies upon the recursive procedure dfs. Algorithm 5 sketches the implementation of the dfs procedure.
while next() |
map() |
dfs() |
dfs() |
map() |
map() |
for all vertices adjacent to |
if evaluate() is |
map() |
dfs() |
Observe that Algorithm 5 produces three mappings as it performs the DFS: the depth first ordering , the vertex depth map , and the predecessor map . These mappings provide useful information concerning the structure of the graph. However, only is actually required by the algorithm. It is initialized with all vertices marked as and updated as each node is visited.
The time complexity of a depth-first search is linear in the size of , i.e. . 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 ) must be maintained for each active vertex . This permits the scan of ’s adjacency list to resume at the point where it was suspended when the exploration of is finished. If you have to rescan the adjacency list of to pick up where you left off, linearity is lost.