Exception has occurred: UnboundLocalError local variable 'depth' referenced before assignment

Thread Starter

terabaaphoonmein

Joined Jul 19, 2020
111
This code is for iterative deepening depth first search in python.

Code:
# Python dictionary to act as an adjacency list
graph = {
  '7' : ['19','21', '14'],
  '19': ['1', '12', '31'],
  '21': [],
  '14': ['23', '6'],
  '1' : [],
  '12': [],
  '31': [],
  '23': [],
  '6' : []
}
visited=[]
goal='31'
depth=0

depth_limit=2
def dls(visited, graph, node,depth_limit):
    if(node==goal):
            print("goal found")
            return True

    
    if(depth>=0):
        #to print path
        if node not in visited:
            visited.append(node)
        
        

        for neighbor in graph[node]:
            dls(visited, graph, neighbor,depth_limit-1)
        

    return False


def iddfs(visited,graph,node):
    while True:
        solution=dls(visited,graph,node,depth_limit)
        if(solution==goal):
            print("Success goal find at depth=",depth)
            print("Path=",visited)     
        depth=depth+1
 
        

print("Following is the Depth-First Search")
iddfs(visited, graph, '7')
There are various pseudocodes available for this problem. They are as follows-:
I did my best to understand and implement the code but I seem to have failed. And it is getting really confusing. Can you help me?

















 
Top