Introduction to Depth-First Search
Explore depth-first search (DFS) to traverse graphs and detect connectivity and cycles. Learn recursive DFS implementation, optimizing traversal, and handling directed and undirected graphs to understand reachability and graph components.
We'll cover the following...
In this lesson, we focus on a particular instantiation of the algorithm called depth-first search and 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
Explanation
- Lines 3–12: These lines define a recursive method
DFSthat performs a depth-first search traversal of a graph represented as an adjacency list. - Lines 14–32: These lines define a graph as an adjacency list and call the
DFSfunction to traverse the graph starting from vertex 1.
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
...