Breadth-first search, layer by layer
After this: Follow breadth-first search with its queue, and read off each node's distance.
On this page · 8 sections · 4 checks
You can now store a graph as an adjacency list. Now we can use it. Here are the four friends again.
How far is each person from Asha, counted in edges? With four people you can see it in the drawing: Ben is 1 edge away, and Dev is 2. With a million people you cannot, so a program needs a method.
Spreading out from the start
Imagine that Asha has some news. On the first day, she tells everyone she knows: Ben and Cara. On the second day, they tell everyone they know who has not heard yet: Dev. The news reaches the closest people first.
Each group is called a layer: all the nodes at the same number of edges from the start. That number is the node's distance. Asha is at distance 0, Ben and Cara are at 1, and Dev is at 2.
A walk that goes through a graph one layer at a time is called , or BFS. "Breadth" means width: the walk spreads wide before it goes further away.
What the walk has to remember
A queue of nodes waiting for their turn. A queue works like a line at a shop. New arrivals join at the back (enqueue), and the next person leaves from the front (dequeue), so the oldest entry leaves first. The lesson on queues explains more.
A set of nodes it has already met. A hash set tells you quickly whether something is in it. Without this set, Asha would add Ben, Ben would add Asha, and the walk would go round forever.
A node is seen when it joins the queue, and visited when it leaves the front. The set in the code is named visited, which is the usual name, but a node goes into it when it is seen. That way, no node can join the queue twice.
The method, step by step
- Put the start node in the queue and mark it as seen. Its distance is 0.
- Take the node at the front of the queue. This is the visit.
- Look at each neighbour of that node. If a neighbour has not been seen, mark it as seen, set its distance to one more than the current node's distance, and add it to the back of the queue.
- Go back to step 2. Stop when the queue is empty.
Here is the method on the four friends, starting from Asha. Neighbours are taken in alphabetical order.
| Step | Visit | What happens | Queue after this step, front first |
|---|---|---|---|
| Start | nobody yet | Asha joins at distance 0. | Asha |
| 1 | Asha | Ben and Cara are both new. They join at distance 1. | Ben, Cara |
| 2 | Ben | Asha has been seen. Dev is new, and joins at distance 2. | Cara, Dev |
| 3 | Cara | Asha and Dev have both been seen. Nobody joins. | Dev |
| 4 | Dev | Ben and Cara have both been seen. Nobody joins. | empty |
The nodes were visited one layer at a time. In step 3, Cara also knows Dev, but Dev has been seen, so Dev does not join a second time.
In step 2, Ben found Dev, so Ben is the of Dev. A node's distance is always its parent's distance plus one.
The code
Here is the same method on the six-node graph, starting at A. It uses the list adj from the last lesson.
from collections import deque
def bfs(adj, start): visited = {start} # seen: in the queue now, or visited already dist = {start: 0} queue = deque([start]) while queue: node = queue.popleft() # the front: the oldest entry print(node, dist[node]) # visit it for nb in adj[node]: if nb not in visited: visited.add(nb) dist[nb] = dist[node] + 1 # one edge further than its parent queue.append(nb) # the back return dist
bfs(adj, "A")A 0 B 1 C 1 D 2 E 3 F 4
static Map<String, Integer> bfs(Map<String, List<String>> adj, String start) { Set<String> visited = new HashSet<>(); // seen: in the queue now, or visited already visited.add(start); Map<String, Integer> dist = new HashMap<>(); dist.put(start, 0); Deque<String> queue = new ArrayDeque<>(); queue.add(start); while (!queue.isEmpty()) { String node = queue.poll(); // the front: the oldest entry System.out.println(node + " " + dist.get(node)); // visit it for (String nb : adj.get(node)) { if (!visited.contains(nb)) { visited.add(nb); dist.put(nb, dist.get(node) + 1); // one edge further than its parent queue.add(nb); // the back } } } return dist;}A 0 B 1 C 1 D 2 E 3 F 4
visitedanddist(short for distance) begin with the start node. This is step 1.- The highlighted lines are the queue. A dequeArrayDeque is a queue that is fast at both ends.
- The
whileloop visits one node each time round, which here means printing it. This is step 2. - The
forloop looks at each neighbour,nbfor short, and handles the new ones. This is step 3.
Why the distances are the fewest edges
A node's distance is set once, when it is first seen. Why is that the smallest possible value?
Nodes leave the queue in order of distance, because new nodes join at the back, behind everything already waiting. So the first neighbour of a node to leave the queue is as close to the start as any of its neighbours, and that neighbour sets the distance. A shorter route cannot turn up later. The node before it on that route would have left the queue earlier, and would have seen it first.
Take Dev. A route of 1 edge would need an edge from Asha to Dev, and Asha, who left the queue first, did not find one.
Watch it happen
Watch the queue strip and the distances under the nodes. The task first asks for a prediction: tap the node you expect to leave the queue third.
- BFS from ARun breadth-first search from A. Watch the queue. B and C join at distance 1. D joins once, from B, at distance 2.
- BFS from F
Pick a start node and run an algorithm.
Check yourself
BFS from A on the six-node graph has visited A, B and C. Which node leaves the queue next?
BFS from A. Two nodes have been visited, A and then B. What is in the queue now, front first?
BFS from A on the six-node graph, with neighbours taken in alphabetical order. In which order are the nodes visited?
The walk is at node, and it has found nb for the first time. Complete the line that records the distance of nb.
def bfs(adj, start): visited = {start} dist = {start: 0} queue = deque([start]) while queue: node = queue.popleft() for nb in adj[node]: if nb not in visited: visited.add(nb) ____________________________ # ← nb is one edge further than node queue.append(nb) return diststatic Map<String, Integer> bfs(Map<String, List<String>> adj, String start) { Set<String> visited = new HashSet<>(); visited.add(start); Map<String, Integer> dist = new HashMap<>(); dist.put(start, 0); Deque<String> queue = new ArrayDeque<>(); queue.add(start); while (!queue.isEmpty()) { String node = queue.poll(); for (String nb : adj.get(node)) { if (!visited.contains(nb)) { visited.add(nb); ____________________________ // ← nb is one edge further than node queue.add(nb); } } } return dist;}Connect
- Follow breadth-first search step by step: take the oldest node from the queue, and add its unseen neighbours, marking them as seen.
- Say what the queue holds after any number of visits.
- Explain why a node's distance is its parent's distance plus one, and why that is the fewest edges.