Python Simple Depth First Search

Source URL: https://favtutor.com/blogs/depth-first-search-python

Language: whatever

Created on: 2021-07-20 09:06:02

# Using a Python dictionary to act as an adjacency list
graph = {
  '5' : ['3','7'],
  '3' : ['2', '4'],
  '7' : ['8'],
  '2' : [],
  '4' : ['8'],
  '8' : []
}

visited = set() # Set to keep track of visited nodes of graph.

def dfs(visited, graph, node):  #function for dfs 
    if node not in visited:
        print (node)
        visited.add(node)
        for neighbour in graph[node]:
            dfs(visited, graph, neighbour)

# Driver Code
print("Following is the Depth-First Search")
dfs(visited, graph, '5')
Understand how to implement depth first search in python with complete source code. We have given a detailed introduction to dfs algorithm.
content_copy