How to implement depth-first search in Python
Depth-first search (DFS), is an algorithm for tree traversal on graph or tree data structures. It can be implemented easily using recursion and data structures like dictionaries and sets.
The Algorithm
- Pick any node. If it is unvisited, mark it as visited and recur on all its adjacent nodes.
- Repeat until all the nodes are visited, or the node to be searched is found.
Implementation
Consider this graph, implemented in the code below:
Coding example
Let's understand how it works with a help of coding example:
# Using a Python dictionary to act as an adjacency listgraph = {'A' : ['B','C'],'B' : ['D', 'E'],'C' : ['F'],'D' : [],'E' : ['F'],'F' : []}visited = set() # Set to keep track of visited nodes.def dfs(visited, graph, node):if node not in visited:print (node)visited.add(node)for neighbour in graph[node]:dfs(visited, graph, neighbour)# Driver Codedfs(visited, graph, 'A')
Explanation
- Lines 2-9: The illustrated graph is represented using an adjacency list - an easy way to do it in Python is to use a dictionary data structure. Each vertex has a list of its adjacent nodes stored.
- Line 11:
visitedis a set that is used to keep track of visited nodes. - Line 21: The
dfsfunction is called and is passed thevisitedset, thegraphin the form of a dictionary, andA, which is the starting node. - Lines 13-18:
dfsfollows the algorithm described above:- It first checks if the current node is unvisited - if yes, it is appended in the
visitedset. - Then for each neighbor of the current node, the
dfsfunction is invoked again. - The base case is invoked when all the nodes are visited. The function then returns.
- It first checks if the current node is unvisited - if yes, it is appended in the
Time Complexity
Since all the nodes and vertices are visited, the average time complexity for DFS on a graph is , where is the number of vertices and is the number of edges. In case of DFS on a tree, the time complexity is , where is the number of nodes.
Note: We say average time complexity because a set’s
inoperation has an average time complexity of . If we used a list, the complexity would be higher.
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved