Introduction to Depth-First Search
Explore the depth-first search (DFS) algorithm with a focus on directed graphs. Understand the recursive implementation, the use of pre-visit and post-visit functions, and how DFS helps determine reachability and spanning trees in graph traversal. Gain knowledge of wrapper functions to traverse entire graphs, including disconnected parts, and differences between directed and undirected graphs in DFS.
We'll cover the following...
In this lesson, we’ll focus on a particular instantiation of the depth-first search algorithm. Primarily, we’ll look at the behavior of this algorithm in directed graphs. Although depth-first search can be accurately described as “whatever-first search with a stack,” the algorithm is normally implemented recursively rather than using an explicit stack:
Algorithm
Implementation
Explanation
-
Line 1: The
dfsfunction takes three arguments:vis the current vertex being visited,markedis the list to keep track of visited vertices, andadjis the adjacency list representation of the graph. -
Lines 2–6: Here, we represent the recursive part of the
dfsfunction. It first marks the current vertexvas visited by settingmarked[v] = True. For each adjacent vertexw, it checks if it has already been visited by checking the corresponding value inmarkedlist. If it has not been visited yet (not marked[w]), then it calls thedfsfunction recursively with the adjacent vertexwas the new starting vertex.
Optimization
We can make this algorithm slightly faster (in practice) by checking whether a node is marked before we recursively explore it. This modification ensures that we call only once for each vertex . We can further modify the algorithm to compute other useful information about the vertices and edges by introducing two black-box subroutines, and , which we leave unspecified for now.
Algorithm
...