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
#include <iostream>#include <vector>using namespace std;void DFS(int v, bool marked[], vector<int> adj[]){marked[v] = true;cout << v << " ";for(int i = 0; i < adj[v].size(); i++){int w = adj[v][i];if(!marked[w])DFS(w, marked, adj);}}int main(){// Define the graph as an adjacency listvector<int> adj[6];adj[1].push_back(2);adj[1].push_back(3);adj[2].push_back(4);adj[3].push_back(4);adj[4].push_back(5);// Define the marked arraybool marked[6] = {false};// Call DFS starting from vertex 1DFS(1, marked, adj);return 0;}
Explanation
-
Line 5: The function
DFS
takes three arguments:v
is the current vertex being visited,marked
is an array to keep track of visited vertices, andadj
is 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
v
as visited by settingmarked[v] = true
. For each adjacent vertexw
, it checks if it has already been visited by checking the corresponding value in themarked
array. If it hasn’t been visited yet (!marked[w]
), then it calls theDFS
function recursively with the adjacent vertexw
as 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 ...
Create a free account to access the full course.
By signing up, you agree to Educative's Terms of Service and Privacy Policy