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 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
def dfs(v, marked, adj):marked[v] = Trueprint(v, end=" ")for w in adj[v]:if not marked[w]:dfs(w, marked, adj)# Define the graph as an adjacency listadj = [[] for i in range(6)]adj[1].extend([2, 3])adj[2].append(4)adj[3].append(4)adj[4].append(5)# Define the marked listmarked = [False] * 6# Call dfs starting from vertex 1dfs(1, marked, adj)
Explanation
-
Line 1: The
dfs
function takes three arguments:v
is the current vertex being visited,marked
is the list to keep track of visited vertices, andadj
is the adjacency list representation of the graph. -
Lines 2â6: Here, we represent the recursive part of the
dfs
function. It first marks the current vertexv
as visited by settingmarked[v] = True
. For each adjacent vertexw
, it checks if it has already been visited by checking the corresponding value inmarked
list. If it has not been visited yet (not 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 , which we leave unspecified for now.
Algorithm
...