Queues in practice
Build a deque-based task runner and implement BFS shortest-path on an adjacency-list graph.
- Implement a task queue with collections.deque
- Implement BFS on an adjacency list to find the shortest path in an unweighted graph
- Trace through BFS to understand how the queue enforces level-by-level ordering
Two programs that use a deque as their core data structure. The first is a
minimal task scheduler; the second is BFS shortest-path — the algorithm that
powers "degrees of separation" problems, social-graph features, and level maps
in games.
Task queue and BFS shortest path
How the BFS path-tracking works
Instead of storing just a node in the queue, we store the entire path from
start to that node. When we dequeue a path, the last element is the current
node. For each unvisited neighbour we append a new path that extends the
current one by one step.
The first time we reach goal, the path in hand is guaranteed to be the
shortest — no shorter path could arrive later, because shorter paths would have
been dequeued first (BFS processes level by level).
The visited set is essential. Without it, BFS would re-enqueue nodes it has
already explored, causing exponential blowup on any graph with cycles.
Storing the full path in the queue uses O(n) extra memory per path. For graphs
where you only need the distance (not the actual path), store just the node and
a separate dist dictionary — you save significant memory on large graphs.
Where to go next
Next: heaps and priority queues — when FIFO is not enough and you need to always process the most important item next.