Search⌘ K

Introduction to Depth-First Search

Explore the depth-first search (DFS) algorithm with a focus on directed graphs. Understand the recursive implementation, the use of pre-visit and post-visit functions, and how DFS helps determine reachability and spanning trees in graph traversal. Gain knowledge of wrapper functions to traverse entire graphs, including disconnected parts, and differences between directed and undirected graphs in DFS.

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

Python 3.5
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


DFS(v):mark vPreVisit(v)for each edge vwif w is unmarkedparent(w ...