Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

dfs algorithm

# Depth First Search: DFS Algorithm

# 1) Pick any node. 
# 2) If it is unvisited, mark it as visited and recur on all its 
#    adjacent (neighbours) nodes. 
# 3) Repeat until all the nodes are visited

graph= {
    'A' : ['B','C'],
    'B' : ['D', 'E'],
    'C' : ['F'],
    'D' : [],
    'E' : ['F'],
    'F' : []
    }
visited = set() # Set to keep track of visited nodes of graph.

def dfs(visited, graph, node):  #function for dfs 
    if node not in visited:
        ''' 
        We start with A
        Then B
        Then D
        Then E
        Then F
        Then C
        A -> B -> D -> E -> F -> C
        '''
        print(node)
        # added to visited to avoid visit the node twice 
        visited.add(node)
        for neighbour in graph[node]:
            ''' 
            * Neighbour of A : B and C but first visit B
            * Then neighbour of B : D and E but first visit D 
            * Then neighbour of D : doesn't have neighbour then backtrack to the neighbour
                of the previous node (B) which is E
            * Then neighbour of E : F
            * Then neighbour of F : doesn't have neighbour then backtrack to the neighbour 
                of the previous node E but doesn't have other neighbour except F which is visited
                So backtracking again to B and B also doesn't have nodes not visited 
                So backtracking again to A: C not visited YAY!
            '''
            dfs(visited, graph, neighbour)
    
print(dfs(visited, graph, 'A'))
Comment

PREVIOUS NEXT
Code Example
Python :: NaN stand for python 
Python :: tuple vs set python 
Python :: django delete model from database 
Python :: gaussian 
Python :: self keyword in python 
Python :: how to use str() 
Python :: how to check if two strings are same in python 
Python :: how to check if variable in python is of what kind 
Python :: how to connect mongodb database with python 
Python :: bayesian model probability 
Python :: oops python self and making an object of a class and calling function 
Python :: pass in python 
Python :: python sort based on multiple keys 
Python :: how to make loop python 
Python :: python if in one line 
Python :: simulation? 
Python :: Interfaces 
Python :: What Is Python Recursive Function in python 
Python :: python child class init 
Python :: python all available paths 
Python :: copy something character ubntil a specific character in python 
Python :: Python - Comment vérifier une corde est vide 
Python :: Using the token to make requests 
Python :: python print over the same line 
Python :: pandas month number to name 
Python :: # str and int mixup in python: 
Python :: pandas mask string contains 
Python :: channel unlock command in discord.py 
Python :: concatenate the next row to the previous row pandas 
Python :: print all elements of dictionary except one in python 
ADD CONTENT
Topic
Content
Source link
Name
5+2 =