ComputeDepth-First Search (DFS) in Python
2 min readFeb 5, 2023
Depth-First Search (DFS) is a method for traversing a graph or tree data structure by visiting all the vertices or nodes as deep as possible before backtracking. DFS can be implemented using a stack or recursion. Here is an example implementation using recursion:
graph = {0: [1, 2], 1: [2], 2: [0, 3], 3: []}
visited = set()
def dfs(start):
print(start, end=" ")
visited.add(start)
for node in graph[start]:
if node not in visited:
dfs(node)
if __name__ == "__main__":
# Example graph
dfs(2) # Output: 2 0 1 3
Explanation:
- The
graph
dictionary represents the adjacency list of the graph, wheregraph[i]
is a list of nodes that nodei
is connected to. - The
visited
set is used to keep track of which nodes have been visited during the DFS. - The
dfs
function takes a starting node as input and performs the DFS. - In the
dfs
function, the starting node is printed and added to thevisited
set. - The
for
loop checks if there is an edge between the current node and an unvisited node. If there is, thedfs
function is called for that node. - The
if __name__ == "__main__"
block is a special Python construct that only executes the code inside if the script is run directly (not imported as a module). - In the main block, the example graph is initialized, and the DFS is started from node 2.