The queue decides the order
BFS keeps a queue of nodes that have been found but not yet explored. It always takes the node that has waited longest (first in, first out), looks at its neighbours, and adds the ones it has not seen to the back. Because a node one edge away always joins the queue before any node two edges away, the nodes come out in order of distance.
The example finds how many edges separate node 0 from node 5. The graph is given as an adjacency list: graph[3] is [1, 2, 4], the neighbours of node 3.
from collections import deque
def shortestPath(graph, start, goal):
dist = {start: 0}
visited = {start}
queue = deque([start])
while queue:
node = queue.popleft()
if node == goal:
return dist[node]
for nei in graph[node]:
if nei not in visited:
visited.add(nei)
dist[nei] = dist[node] + 1
queue.append(nei)
return -1
The run, one node at a time
| Leaves the queue | New neighbours | Queue after | Distance found |
|---|---|---|---|
| 0 | 1, 2 | [1, 2] | 1 and 2 are 1 edge away |
| 1 | 3 (0 was seen) | [2, 3] | 3 is 2 edges away |
| 2 | none (0 and 3 were seen) | [3] | |
| 3 | 4 | [4] | 4 is 3 edges away |
| 4 | 5 | [5] | 5 is 4 edges away |
| 5 | the goal | returns 4 |
Node 3 is reachable from both 1 and 2, but it joins the queue only once: it is marked visited the moment it is added, so when 2 looks at it, it is already taken care of.
Why the first visit is the shortest path
In a graph where every edge counts the same, the queue hands out nodes in order of distance from the start. So the first time BFS reaches a node, it has reached it by a shortest path, and dist[nei] = dist[node] + 1 is final. That is why BFS is the standard answer for shortest paths in unweighted graphs, grids and word ladders. (With weights on the edges you need Dijkstra's algorithm, which swaps the queue for a priority queue.)
What you see in PyVisualizer
The adjacency list is drawn as the graph it describes, with the deque beside it as a queue: nodes leave at the front and join at the back. Nodes change colour as they are queued, examined and visited, the current node and nei are labelled, and each node's distance from dist is written next to it. The visited set and the dist dictionary are drawn too, so you can check each row of the table above against the picture.
Common mistakes
- Marking visited when a node leaves the queue instead of when it joins. The same node can then be added several times, and the run does extra work.
- Using a list as the queue.
list.pop(0)shifts every item along, so each pop costs O(n).collections.dequepops from the front in O(1). - Popping from the wrong end. Take from the back (
pop()) and the queue becomes a stack: that is depth-first search, and the first visit is no longer the shortest.
Try it yourself
- Change the goal to 3 and see the run stop earlier.
- Paste your own BFS over a grid, such as rotting oranges or number of islands, and give the grid as a list of lists.