Sub topic 2
Queues: Why First-In, First-Out Matters
This chapter assumes you can write basic Python and know lists and dictionaries. It also assumes you can read Big-O notation and know what an adjacency list is, which the previous chapter covered. The goal here is to understand the data structure that drives breadth-first search, before you see the full algorithm in the next chapter.
The frontier and its order
Every graph traversal keeps a frontier, the set of vertices that have been discovered but not yet processed. The traversal repeatedly takes one vertex out of the frontier, processes it, and adds that vertex's neighbors. The only thing that decides the traversal's shape is which vertex comes out next.
A queue is a container that removes items in the same order they were added. This is called first-in, first-out (FIFO). A stack removes the most recently added item first, which is last-in, first-out (LIFO). Give a traversal a queue and you get breadth-first search. Give it a stack and you get a depth-first search.
Seeing the difference
The code below runs the same loop twice on a small tree. The only change between the two runs is the end of the frontier the loop removes from. The input is a tree, so no vertex can be reached twice. Graphs with cycles need a visited set, which a later chapter covers.
from collections import deque
tree = {
'root': ['a', 'b'],
'a': ['a1', 'a2'],
'b': ['b1'],
'a1': [], 'a2': [], 'b1': [],
}
def visit_order(tree, start, fifo):
frontier = deque([start])
order = []
while frontier:
node = frontier.popleft() if fifo else frontier.pop()
order.append(node)
frontier.extend(tree[node])
return order
print(visit_order(tree, 'root', fifo=True)) # ['root', 'a', 'b', 'a1', 'a2', 'b1']
print(visit_order(tree, 'root', fifo=False)) # ['root', 'b', 'b1', 'a', 'a2', 'a1']With the queue, the loop finishes every vertex one edge from the root before it touches any vertex two edges away. This happens because the children of a and b join the back of the queue, behind everything discovered earlier. With the stack, the loop goes deep down b first and only then returns to a.
That ordering is the reason BFS finds shortest paths in unweighted graphs. The chapter on layers and distances proves it.
Choosing the right container in Python
Python has no built-in type named "queue" for this job. Many people use a list, and that causes a slowdown that is easy to miss.
| Operation | `list` | `collections.deque` |
|---|---|---|
| Add at back | `append`, O(1) amortized | `append`, O(1) |
| Remove from front | `pop(0)`, O(n) | `popleft()`, O(1) |
| Remove from back | `pop()`, O(1) | `pop()`, O(1) |
list.pop(0) shifts every remaining element left by one slot. deque is a double-ended queue built from linked blocks, so removing from either end takes constant time.
from collections import deque
q = deque()
q.append('A')
q.append('B')
q.append('C')
print(q.popleft()) # A
print(q.popleft()) # B
q.append('D')
print(list(q)) # ['C', 'D']Common mistakes
- Calling
pop()on a deque when you meantpopleft(). The code still runs, but the search silently becomes depth-first. - Using
appendlefttogether withpopleft. That also produces LIFO order. - Using
extendwhen you meantappendwith a single string.q.extend('AB')adds'A'and'B'as two separate items.
Exercise
In the tree example, suppose the line is changed to node = frontier.pop() and frontier.extend(tree[node]) is replaced by frontier.extend(reversed(tree[node])). What order is printed, and is it breadth-first?
Show answer
['root', 'a', 'a1', 'a2', 'b', 'b1']. It is not breadth-first. Reversing the children only changes which branch the stack explores first. The traversal is still depth-first, because the most recently added vertex always comes out next.
Exercise
A graph has 100,000 vertices, and a BFS on it uses a list with pop(0). Roughly how many element shifts can the front removals cost in total, and what one-line change fixes it?
Show answer
Each pop(0) can shift up to the full length of the queue, so the total can approach the order of n squared, around 10^10 shifts in the worst case. Store the frontier in collections.deque and call popleft(), which makes each removal O(1).