Sub topic 9
Breadth-first search with a queue
This chapter assumes you can read Python functions, use dictionaries and sets, and know that collections.deque gives O(1) appends and pops at both ends. Here you will see why a FIFO queue is the right structure for breadth-first search (BFS).
What BFS does
BFS is a graph traversal that visits nodes in order of their distance from a start node. Distance means the number of edges on the path. It visits every node one edge away, then every node two edges away, and so on.
A FIFO queue produces this order. Newly discovered nodes go to the back. The next node to expand comes from the front. Nodes found earlier are closer to the start, so they are expanded first. The queue's contents at any moment are called the frontier.
Shortest path length
In an unweighted graph, the first time BFS reaches a node is along a path with the fewest edges. The function below returns that edge count. Each queue entry stores the node and its distance from the start.
from collections import deque
def shortest_path_length(graph, start, goal):
if start == goal:
return 0
seen = {start}
frontier = deque([(start, 0)])
while frontier:
node, dist = frontier.popleft()
for nxt in graph.get(node, ()):
if nxt == goal:
return dist + 1
if nxt not in seen:
seen.add(nxt)
frontier.append((nxt, dist + 1))
return -1
graph = {"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": ["E"]}
print(shortest_path_length(graph, "A", "E")) # 3Trace the run on this graph:
- The queue holds
(A, 0). Popping it adds(B, 1)and(C, 1). - Popping
Badds(D, 2). - Popping
CfindsDalready seen, so nothing is added. - Popping
DfindsE, the goal, and returns2 + 1 = 3.
The graph.get(node, ()) call handles nodes that have no entry in the dictionary, such as E. They are treated as having no neighbors. The function returns -1 when the queue empties without reaching the goal.
Recovering the path itself
Often you need the route, not only its length. Store each node's parent when you first discover it. A parent dictionary can also serve as the seen set, because a node is seen exactly when it has a parent entry. After reaching the goal, follow the parents back to the start and reverse the result.
from collections import deque
def shortest_path(graph, start, goal):
parent = {start: None}
frontier = deque([start])
while frontier:
node = frontier.popleft()
if node == goal:
path = []
while node is not None:
path.append(node)
node = parent[node]
return path[::-1]
for nxt in graph.get(node, ()):
if nxt not in parent:
parent[nxt] = node
frontier.append(nxt)
return None
graph = {"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": ["E"]}
print(shortest_path(graph, "A", "E")) # ['A', 'B', 'D', 'E']D can be reached through B or C. B was expanded first, so it became D's parent. Both routes have the same length, and BFS returns whichever it finds first.
Common errors
- Marking nodes as seen too late. If you add a node to
seenwhen you pop it, the same node can enter the queue several times before it is popped. In the example,Dwould be queued twice. On dense graphs this wastes time and memory. Mark a node when you push it. - Using
list.pop(0). Each call shifts every remaining element, so dequeue costs O(n). Over a whole search this can turn an O(V + E) algorithm into something much slower. Usedeque.popleft(). - Using
pop()instead ofpopleft(). Removing from the right end makes the container a stack. The search then becomes depth-first, and the first path it finds is not guaranteed to be the shortest. - Skipping the seen set. Graphs with cycles will loop forever without it.
- Using BFS on weighted graphs. BFS counts edges, not total weight. For weighted edges you need Dijkstra's algorithm, which uses a priority queue, covered in a later chapter.
Where else BFS appears
The same loop solves many problems. Grid mazes treat each cell as a node and its open neighbors as edges. Word ladders treat each word as a node and words that differ by one letter as edges. Level-order tree traversal is BFS on a tree, where no seen set is needed because trees have no cycles.
Exercise
In shortestpathlength, suppose you remove the seen set and the if nxt not in seen check, and run it on the graph {"A": ["B"], "B": ["A"]} with goal "Z". What happens, and why?
Show answer
It never terminates. A is expanded and B is queued, then B is expanded and A is queued again, and this repeats forever. The graph has a cycle and nothing records that nodes were already visited. The queue never becomes empty, so the return -1 line is never reached.
Exercise
Why does a BFS that uses a deque with pop() (removing from the right) instead of popleft() stop guaranteeing the shortest path?
Show answer
pop() removes the most recently added node, so the container behaves as a LIFO stack and the search goes deep along one branch first (depth-first). Nodes are no longer expanded in order of distance, so the first time the goal is reached may be along a longer path.