Context-: Artificial Intelligence. Uninformed search. Depth first search. The goal of course seems to understand the properties, but I am trying to learn first the algorithm itself to understand thsoe stuffs.
This is the tree I am working with-: Tree figure
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 = [] # List of visited nodes of graph.
def dfs(visited, graph, node):
if node not in visited:
visited.append(node)
for neighbor in graph[node]:
dfs(visited, graph, neighbor)
print(node)
# Driver Code
print("Following is the Depth-First Search")
dfs(visited, graph, '7')
print("visited=",visited)
My dry run of this program-:
I will try to explain what is my problem, step by step. steps-:
dfs(visited,graph,7)
7 not in visited.
visited=7
dfs(19)
- 19 not in visited.
visited=7,19
dfs(1)
- 1 not in visited
visited=7,19,1
1 has no neighbours.
print(1)
imo the code should stop now. Because there is no function call no nth. But in fact the code goes to somewhere else and 12 gets printed. I don't understand this at all. There is no function call no nth, how does the code goes and prints 12. I don't understand this thing.
I tried visualizing from here and it was too confusing as you can do it yourself on that step after it prints 1, it becomes confusing.
https://cscircles.cemc.uwaterloo.ca/visualize#mode=display
Here is the thing what happens in figure
I understand this figure, but I don't understand how it happens.
I have asked this question in several forums and I am coming here at stackoverflow at last.
You're calling a function in a function in a function. When dfs(1) is done executing, it will return to where dfs(19) left off. When dfs(19) is done executing, it will return to where dfs(7) left off. Something with a function return address and a stack. A real programmer, not me, can probably explain how this works exactly.
After visiting node '1' the program returns to where it came from, i.e. node '19' and goes on to the next child, which is '12'.
dfs(7) calls dfs(19). dfs(7) itself does not go away, it's still around, waiting for dfs(19) to return. Same for dfs(19) calling dfs(1). As soon as dfs(1) returns dfs(19) executes the next loop iteration: dfs(12). And when dfs(19) returns dfs(7) will continue to dfs(21).