Go as deep as you can along one path before backing up. Recursion keeps track of where to come back to.
Python · intermediate · 7 min · 30 steps · free
graph = {'A': ['B', 'C'], 'B': ['D'], 'C': ['D'], 'D': []}
def dfs(node, visited):
visited.append(node)
for neighbor in graph[node]:
if neighbor not in visited:
dfs(neighbor, visited)
return visited
print(dfs('A', []))graph is created and points to a new dict: {A: a list, B: a list, C: a list, D: a list}.dfs(). Its body does not run yet: it runs each time the function is called.dfs(), with node = 'A' and visited = []. It gets its own names.visited points to.neighbor is created with the value 'B'.neighbor not in visited is true, so the block under it runs.visited points to.neighbor is created with the value 'D'.neighbor not in visited is true, so the block under it runs.visited points to.for neighbor in graph[node].visited.dfs() #3 has finished, so its names are gone.for neighbor in graph[node].visited.neighbor changes from 'B' to 'C'.neighbor not in visited is true, so the block under it runs.dfs() #2, with node = 'C' and visited = ['A', 'B', 'D']. It gets its own names.visited points to.neighbor is created with the value 'D'.for neighbor in graph[node].visited.dfs() #2 has finished, so its names are gone.for neighbor in graph[node].visited.dfs() has finished, so its names are gone. It prints ['A', 'B', 'D', 'C'].Answer: A, B, C, D. Level by level.
Answer: A stack (the call stack)
← Breadth-First Search · Dijkstra's Shortest Paths →