Lesson 3 of 6
Breadth-first search
Breadth-first search walks a graph in rings, nearest first. A queue keeps that order, so the first time the walk reaches a node, it got there by a path with the fewest edges.
Trace breadth-first search with a deque and a visited set, and say what the queue holds after each step
Explain why the first time BFS reaches a node is by a shortest path, and why a node is marked visited as it joins the queue
Find shortest paths on a grid with a directions list and a bounds check
Start one search from many sources at once and count its rounds as minutes
Search a graph that is never stored by making each node's neighbors when it leaves the queue
A bad batch landed in table A. Table F feeds a dashboard, and your manager asks: how many pipeline hops sit between them? In a lineage graph, each table points to the tables built from it. So this is a directed graph, and the question is the length of the shortest path from A to F, counted in edges.
Depth-first search, from the last lesson, tells you whether F can be reached. It does not tell you how far, because it follows one route as deep as it goes, and the first route it finds can be long. This lesson builds the walk that spreads out evenly, one step at a time in every direction, so the first route it finds to any node is a shortest one.
It is called breadth-first search, or BFS. It answers "fewest steps" questions on an unweighted graph, one where every edge counts as one step: fewest moves through a maze, fewest minutes for rot to spread, fewest letter changes from one word to another.
Rings, nearest first
Which walk finds the nearest nodes first? Visit the start, then every node one edge away, then every node two edges away, and so on. Call each of those groups a ring: ring k holds the nodes whose shortest path from the start has k edges.
The tool that keeps that order is a queue, a line where items join at the back and leave from the front, so the item that has waited longest leaves first. Python's collections.deque does both ends in O(1): queue.append(x) joins at the back, queue.popleft() leaves from the front. BFS takes a node from the front and sends its new neighbors to the back. Module 8's lesson "Level by level" walked a tree this way, one level at a time.
A graph adds one problem: two routes can reach the same node. In a tree, every node has one parent, so it joins the queue once. In a graph, with no check, a node would join once for every route that reaches it, and around a cycle the walk would never end. So a set called visited remembers every node that has ever joined the queue, and no node joins twice: the job seen did in the last two lessons. Each item in the queue is a tuple of two values, a node and its distance from the start, such as ("B", 1). The line node, dist = queue.popleft() takes the front tuple and unpacks it into two names.
Here is the lineage, with an arrow from each table to every table built from it. A feeds B and C, B feeds D, C feeds D and E, and D and E both feed F:
A ---> B ---> D ---> F
| ^ ^
+---> C ------+ |
| |
+----> E ------+
In the code it is an adjacency list: a dict that maps each node to the list of its neighbors. Before you step through, write down ring 1 and ring 2 from A, and guess what hops returns.
from collections import dequegraph = {"A": ["B", "C"],"B": ["D"],"C": ["D", "E"],"D": ["F"],"E": ["F"],"F": [],}def hops(graph, start, goal):queue = deque([(start, 0)])visited = {start}while queue:node, dist = queue.popleft()if node == goal:return distfor neighbor in graph[node]:if neighbor not in visited:visited.add(neighbor)queue.append((neighbor, dist + 1))return -1
(nothing printed yet)The queue handed out the nodes ring by ring:
| Ring (hops from A) | Nodes |
|---|---|
| 0 | A |
| 1 | B, C |
| 2 | D, E |
| 3 | F |
The queue is the rings, laid end to end. At any moment it holds at most two distances: the ring that is leaving, at the front, and the next ring, growing at the back. Inside a ring, nodes leave in the order they joined. Test that on a new graph.
The same breadth-first search on a different graph, with a print in place of the goal check. The five nodes form a circle: A, D, E, C, B, and back to A. Type exactly what it prints.
from collections import deque
graph = {"A": ["D", "B"], "B": ["A", "C"], "C": ["B", "E"], "D": ["A", "E"], "E": ["C", "D"]}
queue = deque([("A", 0)])
visited = {"A"}
while queue:
node, dist = queue.popleft()
print(node, dist)
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append((neighbor, dist + 1))
Why the first arrival is the shortest
hops returned the moment F left the queue, without comparing routes. F was reached twice: from D, and again from E, whose route was ignored because F had already joined. Why is the first route that reaches a node always a shortest one?
Start at ring 0. The queue holds only the start. When it leaves, every node one edge away joins with distance 1: that is ring 1, and nothing else.
Now say the queue holds exactly ring k, and every node of the earlier rings has already joined. As the ring k nodes leave, each sends the neighbors that have not joined yet, with distance k + 1. Such a neighbor is one edge past ring k, so at most k + 1 edges from the start, and it is not in ring k or earlier, because all of those have joined. So it is in ring k + 1. No node of ring k + 1 is missed either: the node right before it on a shortest path is in ring k, and sends it unless another node of ring k already has. So when ring k has left, the queue holds exactly ring k + 1. A whole ring leaves before any node of the next ring does, and every node joins carrying its ring number as its distance, the goal included.
The proof needs every edge to count the same. If one edge took 5 minutes and another 1, a path with fewer edges could take longer. Weighted edges are the job of Dijkstra's algorithm, the last lesson of this module.
One detail in the code makes the cost work: line 21 marks a neighbor visited the moment it joins the queue, not when it leaves. Marking it when you take it out feels natural, since that is when you look at it. Predict what that does.
This version marks a node visited when it leaves the queue instead of when it joins. It runs on the lineage graph from the trace, with no goal. Type exactly what it prints.
from collections import deque
graph = {"A": ["B", "C"], "B": ["D"], "C": ["D", "E"], "D": ["F"], "E": ["F"], "F": []}
queue = deque(["A"])
visited = set()
while queue:
node = queue.popleft()
print(node)
visited.add(node) # marked when it leaves, not when it joins
for neighbor in graph[node]:
if neighbor not in visited:
queue.append(neighbor)
Here is the whole walk in the four questions this course asks of every algorithm:
The E in the cost is the neighbor checks. Count them on the circle from the first exercise.
Go back to the circle program in the first exercise of this lesson (A, D, E, C, B, and back to A). From start to finish, how many times does the line if neighbor not in visited: run? Type a whole number.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
To recap: a queue hands out nodes in rings, the distance a node gets when it joins is its shortest, and marking on joining keeps every node to one trip through the queue. Now write it without the trace. This version keeps no goal and returns every distance; a dict of distances can do the visited set's job.
Write distances(graph, start), which returns a dict mapping every node reachable from start to the fewest edges from start to it. graph is an adjacency list: a dict mapping each node to the list of its neighbors. Leave out nodes that cannot be reached. Then press Watch it run and watch the dict fill ring by ring.
raise NotImplementedError, then press Run tests. Each check says what it expects.Shortest paths on a grid
Maze and map questions arrive as grids, not adjacency lists. Each open cell is a node, and its neighbors are the cells next to it that are inside the grid and not walls. As in the first lesson of this module, a cell's neighbors come from a list of directions, each a change in row and a change in column, plus a bounds check:
directions = [(-1, 0), (0, 1), (1, 0), (0, -1)] # up, right, down, left
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] != "#":
... # (nr, nc) is a neighbor of (r, c)
The search itself does not change. The figure runs BFS on a 4 × 4 grid with three walls (#), from S in the top-left corner to E in the bottom-right. Cells are named (row, column), counting from 0, and each cell checks its neighbors in the order of the list above: up, right, down, left. Each cell is labelled with its distance when it joins the queue, and the queue is listed front to back.
Going down the left side and along the bottom is also 6 moves. There can be several shortest paths, and BFS finds one of them: each cell's link points to the cell that reached it first. Depth-first search found a path, but not a short one.
The first problem is this search with two changes. Diagonal steps are allowed, so there are 8 directions instead of 4. And the answer counts cells, not moves, so the start carries length 1 instead of 0. The grid holds numbers, 0 for open and 1 for blocked, and either corner can be blocked, so check both before you search.
The solution is hops on a grid: (row, col, length) triples in the queue, a directions list with all 8 pairs, and a visited set marked as each cell joins. Every cell joins the queue at most once, so the time is O(n2) for an n × n grid, while the depth-first brute force can lower a cell's number many times and search again from it each time.
Many starts at once
In a crate of oranges, rot spreads from every rotten orange in the same minute. A search from one rotten orange would get the minutes wrong, because an orange rots at its distance from the nearest rotten one. So put every source in the queue before the walk starts, all at distance 0. This is a multi-source BFS. Ring 0 is all the sources together, ring 1 is everything one step from the nearest source, and so on.
The question asks for minutes, so we count rings instead of storing a distance with each item. Recall the round trick from the lesson "Level by level" in module 8: at the start of a round the queue holds exactly one ring, so for _ in range(len(queue)) takes that ring and nothing more. range reads the length once, before the round starts, so the oranges that join during the round wait for the next one. (_ is the usual name for a loop variable the body never uses.) One round is one minute.
Here is the smallest crate: one shelf, where 2 is a rotten orange, 1 a fresh one and 0 an empty spot. A shelf position's neighbors are the positions to its left and right. Before you step through, guess the minutes for [2, 1, 1, 1, 1, 2], and the minutes for [2, 1, 1, 1, 1, 0], where the right end is empty.
from collections import dequedef minutes_to_rot(shelf):queue = deque()fresh = 0for i in range(len(shelf)):if shelf[i] == 2:queue.append(i)elif shelf[i] == 1:fresh += 1minutes = 0while queue and fresh > 0:for _ in range(len(queue)):i = queue.popleft()for j in (i - 1, i + 1):if 0 <= j < len(shelf) and shelf[j] == 1:shelf[j] = 2fresh -= 1queue.append(j)minutes += 1return minutes if fresh == 0 else -1
(nothing printed yet)Writing 2 into the shelf does the visited set's job: a rotten orange never passes the shelf[j] == 1 test again. And the fresh > 0 test stops the loop as soon as the last orange turns, so no empty round adds a minute.
A shelf with no fresh orange takes 0 minutes, and a fresh orange the rot cannot reach gives -1. [2, 0, 2] fails the fresh > 0 test at once and returns 0. In [2, 0, 1] the empty spot cuts the fresh orange off: the first round rots nothing, the queue runs out with fresh still 1, and the last line returns -1.
Now run one on paper, on a small grid where the rot comes from two corners.
A crate as a grid: 0 is empty, 1 is a fresh orange, 2 is a rotten one. Each minute, every fresh orange that shares a side with a rotten one rots.
2 1 1 1
1 0 0 1
1 1 1 2
On paper, run the search from both rotten oranges at once. Write the minute each orange rots in its cell, one round at a time. How many minutes until no fresh orange is left? Cells are (row, column), counting from 0.
Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
The problem is the shelf turned into a crate: a grid with 4 directions, and every rotten orange found by a scan of the whole grid before the first round.
The rounds, the fresh counter and the 2 written into each cell are all from the shelf. Starting every rotten orange together is what makes each round exactly one minute. The practice bank's Distance to the nearest zero (LeetCode 542, 01 Matrix) is the same search with every 0 as a source: a cell's ring number is its distance to the nearest 0.
Neighbors you make yourself
In the last problem of this lesson, the graph is never given. The nodes are words, and two words are joined when they differ in exactly one position. When the graph is not stored, make a node's neighbors at the moment it leaves the queue, and keep only the ones that are real.
A smaller puzzle first. A calculator shows 2 and has two buttons: one adds 1, the other doubles. What is the fewest presses to show 9? Every number is a node, and the neighbors of a number x are x + 1 and x × 2. Numbers above 9 are skipped: both buttons only make a number bigger, so a number past 9 can never come back to 9. Before you step through, find the answer by hand.
from collections import dequedef fewest_presses(start, target):queue = deque([(start, 0)])visited = {start}while queue:x, presses = queue.popleft()if x == target:return pressesfor candidate in (x + 1, x * 2):if candidate <= target and candidate not in visited:visited.add(candidate)queue.append((candidate, presses + 1))return -1
(nothing printed yet)The search is hops again; only the neighbor lines changed. For words, a word's neighbors come from changing one position at a time to each letter, then asking a set whether the result is a word. For "cot" that means "?ot", "c?t" and "co?": 3 positions times 26 letters, at most 78 candidates however long the word list is. Build that part first.
Put the lines in order to build one_letter_neighbors(word, words), which returns every word in the set words that differs from word in exactly one position, found position by position and letter by letter. word[:i] is everything before position i, and word[i + 1:] is everything after it. Indentation is part of each line. Two of the lines do not belong.
Add lines from the list below, in order.
before, after = word[:i], word[i:]if candidate != word and candidate in words:before, after = word[:i], word[i + 1:]for i in range(len(word)):found = []found.append(candidate)for letter in "abcdefghijklmnopqrstuvwxyz":def one_letter_neighbors(word, words):if candidate in words:candidate = before + letter + afterreturn found
Word ladder puts it together. The answer counts words, so the start carries length 1, and the start word does not have to be in the list.
The solution tries only the letters that appear in the list, since no other letter can make a listed word. Making 26 × L candidates per word, for words of length L, beats comparing every pair of words once the list is long: N words make about N2 / 2 pairs.
Before an interview, practice picking the walk from the question alone.
Which of these questions needs breadth-first search, and not depth-first search?
Choose one answer, then check.
Last, say it the way you would in the room.
You have solved the shortest clear path in a grid with breadth-first search. The interviewer asks: "Why BFS and not DFS? And what does it cost?" Write what you would say, in a few plain sentences.
Saved in this browser as you type.