...

/

Introduction to Depth-First Search

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


DFS(v):if v is unmarkedmark vfor each edge vwDFS(w) \underline{DFS(v):} \\ \hspace{0.4cm} if\space v\space is\space unmarked \\ \hspace{1cm} mark\space v \\ \hspace{1cm} for\space each\space edge\space v\rightarrow w \\ \hspace{1.7cm} DFS(w)


Implementation

Press + to interact
def dfs(v, marked, adj):
marked[v] = True
print(v, end=" ")
for w in adj[v]:
if not marked[w]:
dfs(w, marked, adj)
# Define the graph as an adjacency list
adj = [[] 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 list
marked = [False] * 6
# Call dfs starting from vertex 1
dfs(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, and adj 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 vertex v as visited by setting marked[v] = True. For each adjacent vertex w, it checks if it has already been visited by checking the corresponding value in marked list. If it has not been visited yet (not marked[w]), then it calls the dfs function recursively with the adjacent vertex w 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 DFS(v)DFS(v) only once for each vertex vv. We can further modify the algorithm to compute other useful information about the vertices and edges by introducing two black-box subroutines, PreVisitPreVisit and PostVisitPostVisit, which we leave unspecified for now.

Algorithm


...

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy