How to implement Depth First Search algorithm in Python

This Python tutorial helps you to understand what is Depth First Search algorithm and how Python implements DFS.

Algorithm for DFS in Python

This algorithm is a recursive algorithm which follows the concept of backtracking and implemented using stack data structure. But, what is backtracking.

Backtracking:-



It means whenever a tree or a graph is moving forward and there are no nodes along the existing path, the tree moves backwards along the same path which it went forward in order to find new nodes to traverse. This process keeps on iterating until all the unvisited nodes are visited.

How stack is implemented in DFS:-

  1. Select a starting node, mark the starting node as visited and push it into the stack.
  2. Explore any one of adjacent nodes of the starting node which are unvisited.
  3. Mark the unvisited node as visited and push it into the stack.
  4. Repeat this process until all the nodes in the tree or graph are visited.
  5. Once all the nodes are visited, then pop all the elements in the stack until the stack becomes empty.

 

               Implementation of DFS in Python

Source Code: DFS in Python

import sys


def ret_graph():
    return {
        'A': {'B':5.5, 'C':2, 'D':6},
        'B': {'A':5.5, 'E':3},
        'C': {'A':2, 'F':2.5},
        'D': {'A':6, 'F':1.5},
        'E': {'B':3, 'J':7},
        'F': {'C':2.5, 'D':1.5, 'K':1.5, 'G':3.5},
        'G': {'F':3.5, 'I':4},
        'H': {'J':2},
        'I': {'G':4, 'J':4},
        'J': {'H':2, 'I':4},
        'K': {'F':1.5}
    }





start = 'A'                 
dest = 'J'                  
visited = []                
stack = []                  
graph = ret_graph()
path = []


stack.append(start)                  
visited.append(start)                
while stack:                         
    curr = stack.pop()            
    path.append(curr)
    for neigh in graph[curr]:        
        if neigh not in visited:       
            visited.append(neigh)       
            stack.append(neigh)         
            if neigh == end:            
                print("FOUND:", neigh)
                print(path)
                sys.exit(0)
print("Not found")
print(path)

Explanation:

  1. First, create a graph in a function.
  2. Intialize a starting node and destination node.
  3. Create a list for the visited nodes and stack for the next node to be visited.
  4. Call the graph function.
  5.  Initially, the stack is empty.Push the starting node into the stack (stack.append(start) ).
  6. Mark the starting node as visited (visited.append(start) ).
  7. Repeat this process until all the neighbours are visited in the stack till the destination node is found.
  8. If the destination node is found exit the while loop.
  9. If the destination node is not present then “Not found” is printed.
  10. Finally, print the path from starting node to the destination node.

 

You can also read,

 

Leave a Reply

Your email address will not be published. Required fields are marked *