Introduction to Depth-First Search
Learn about the history and evolution of depth-first search.
We'll cover the following...
In this lesson, we’ll focus on a particular instantiation of this algorithm called depth-first search, primarily on 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 5: The function
DFStakes three arguments:vis the current vertex being visited,markedis an array to keep track of visited vertices, andadjis the adjacency list representation of the graph. -
Lines 7–14: The above block of code is the recursive part of the DFS algorithm. It first marks the current vertex
vas visited by settingmarked[v] = true. For each adjacent vertexw, it checks if it has already been visited by checking the corresponding value in themarkedarray. If it hasn’t been visited yet (!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
...