Depth-First Search

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

What you'll learn

dfs.py

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', []))

Step by step

  1. graph is created and points to a new dict: {A: a list, B: a list, C: a list, D: a list}.
  2. Python defines the function dfs(). Its body does not run yet: it runs each time the function is called.
  3. Python calls dfs(), with node = 'A' and visited = []. It gets its own names.
  4. 'A' is added to the end of the list that visited points to.
  5. neighbor is created with the value 'B'.
  6. neighbor not in visited is true, so the block under it runs.
  7. From A, go straight to B, before looking at C.
  8. 'B' is added to the end of the list that visited points to.
  9. neighbor is created with the value 'D'.
  10. neighbor not in visited is true, so the block under it runs.
  11. From B, go deeper to D.
  12. 'D' is added to the end of the list that visited points to.
  13. Python moves to the next item of the loop: for neighbor in graph[node].
  14. The function returns visited.
  15. dfs() #3 has finished, so its names are gone.
  16. Python moves to the next item of the loop: for neighbor in graph[node].
  17. The function returns visited.
  18. D and B are finished; back in A's call, the loop moves on to C.
  19. neighbor changes from 'B' to 'C'.
  20. neighbor not in visited is true, so the block under it runs.
  21. Python calls dfs() #2, with node = 'C' and visited = ['A', 'B', 'D']. It gets its own names.
  22. 'C' is added to the end of the list that visited points to.
  23. neighbor is created with the value 'D'.
  24. D was already visited, so C does not go there again.
  25. Python moves to the next item of the loop: for neighbor in graph[node].
  26. The function returns visited.
  27. dfs() #2 has finished, so its names are gone.
  28. Python moves to the next item of the loop: for neighbor in graph[node].
  29. The function returns visited.
  30. dfs() has finished, so its names are gone. It prints ['A', 'B', 'D', 'C'].

Common mistakes

Best practices

Key takeaways

Check yourself

BFS order on the same graph?

Answer: A, B, C, D. Level by level.

DFS uses which structure?

Answer: A stack (the call stack)

·

More in Graphs