Breadth-First Search

Explore a graph level by level with a queue of paths, and find the shortest route from A to E.

Python · intermediate · 9 min · 49 steps · free

What you'll learn

bfs.py

graph = {'A': ['B', 'C'], 'B': ['D'], 'C': ['E'], 'D': ['E'], 'E': []}

def bfs(start, goal):
    queue = [[start]]
    visited = {start}
    while queue:
        path = queue.pop(0)
        node = path[-1]
        if node == goal:
            return path
        for neighbor in graph[node]:
            if neighbor not in visited:
                visited.add(neighbor)
                queue.append(path + [neighbor])
    return None

print(bfs('A', 'E'))

Step by step

  1. The graph as an adjacency list: each node lists the nodes it connects to.
  2. Python defines the function bfs(). Its body does not run yet: it runs each time the function is called.
  3. Python calls bfs(), with start = 'A' and goal = 'E'. It gets its own names.
  4. The queue holds whole paths. It starts with just ["A"].
  5. visited is created and points to a new set: ['A'].
  6. queue is true, so the loop body runs.
  7. path is created and points to a new list: ['A']. a list is removed from the end of the list that queue points to.
  8. node is created with the value 'A'.
  9. node == goal is false, so the block under it is skipped.
  10. neighbor is created with the value 'B'.
  11. neighbor not in visited is true, so the block under it runs.
  12. 'B' is added to the end of the set that visited points to.
  13. ["A", "B"] joins the back of the queue.
  14. neighbor changes from 'B' to 'C'.
  15. neighbor not in visited is true, so the block under it runs.
  16. 'C' is added to the end of the set that visited points to.
  17. a list is added to the end of the list that queue points to.
  18. Python moves to the next item of the loop: for neighbor in graph[node].
  19. queue is true, so the loop body runs.
  20. Paths come out in the order they went in: all 1-step paths before any 2-step path.
  21. node changes from 'A' to 'B'.
  22. node == goal is false, so the block under it is skipped.
  23. neighbor changes from 'C' to 'D'.
  24. neighbor not in visited is true, so the block under it runs.
  25. 'D' is added to the end of the set that visited points to.
  26. a list is added to the end of the list that queue points to.
  27. Python moves to the next item of the loop: for neighbor in graph[node].
  28. queue is true, so the loop body runs.
  29. path now points to a different list: ['A', 'C']. a list is removed from the start of the list that queue points to.
  30. node changes from 'B' to 'C'.
  31. node == goal is false, so the block under it is skipped.
  32. neighbor changes from 'D' to 'E'.
  33. neighbor not in visited is true, so the block under it runs.
  34. 'E' is added to the end of the set that visited points to.
  35. a list is added to the end of the list that queue points to.
  36. Python moves to the next item of the loop: for neighbor in graph[node].
  37. queue is true, so the loop body runs.
  38. path now points to a different list: ['A', 'B', 'D']. a list is removed from the start of the list that queue points to.
  39. node changes from 'C' to 'D'.
  40. node == goal is false, so the block under it is skipped.
  41. Python moves to the next item of the loop: for neighbor in graph[node].
  42. neighbor not in visited is false, so the block under it is skipped.
  43. Python moves to the next item of the loop: for neighbor in graph[node].
  44. queue is true, so the loop body runs.
  45. path now points to a different list: ['A', 'C', 'E']. a list is removed from the end of the list that queue points to.
  46. node changes from 'D' to 'E'.
  47. E reached via A → C → E.
  48. The function returns path.
  49. bfs() has finished, so its names are gone. It prints ['A', 'C', 'E'].

Common mistakes

Best practices

Key takeaways

Check yourself

Data structure behind BFS?

Answer: Queue

Why keep visited?

Answer: To avoid going round in circles

·

More in Graphs