I am building a depth first search function which is used on an undirected adjacency list. This function is meant to put all paths that successfully find the target node into the viable functions list and the non-viable paths into culdesac.
adjacencylist={1:[2,3],2:[1,4],3:[1,5],4:[2],5:[3]}
visited=[]
culdesacs=[]
viablepaths=[]
def dfs(graph,node,target,path,output):
if node in visited:
return
visited.append(node)
print(path)
if node==target:
output.append(path)
viablepaths.append(output)
return print('hello')
for nx in graph[node]:
dfs(graph,nx,5,path+[nx],output)
for element in path:
if element not in culdesacs:
culdesacs.append(element)
print(path)
print(culdesacs)
return print('oops')
dfs(adjacencylist,1,5,[1],[])
What I don't understand is why my function continues to work even after successfully hitting the target and even triggering the base case of my recursive program. For example in the function call dfs(adjacencylist,1,5,[1],[]), my starting node is 1 and my target node is 5. My function successfully found the path [1,3,5] and returned "hello". But then it continues to print oops and printing the paths [1,3] and [1]. Ideally, once it found the path[1,3,5], i would just like it to end the function altogether
How can I fix this
The problem is the following: When you're in
for nx in graph[node]:
dfs(graph,nx,5,path+[nx],output)
you start the recursive call that finds the target.
However, you do not return e.g. true
in
if node==target:
output.append(path)
viablepaths.append(output)
return print('hello')
an do not check the return value.
I would recommend reading up on the beahvior of the call stack. Just because you end the recursive call that finds the value, the others are not cancelled