iq.lab
Python starts when a code cell comes near or you run one
10 Graphs

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.

About 2 hours, with the 3 problems worked in it
By the end you can
  • 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.

Step throughFewest hops from A to F
Step 1 of 61
Line 1 is about to run.
from collections import deque
graph = {
"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 dist
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append((neighbor, dist + 1))
return -1
Names
no names yet
Output
(nothing printed yet)

The queue handed out the nodes ring by ring:

Ring (hops from A)Nodes
0A
1B, C
2D, E
3F

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.

PredictWho leaves first

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.

PredictMarking too late

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.

Work it outCounting the neighbor checks

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.

checks

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.

Code itEvery distance from the start

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.

⌘+Enter runsPython starts when a code cell comes near or you run one
Write your code where the starter says 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.

mediumBreadth-first search target 25 min

Shortest clear path in a grid

A square grid grid has n rows and n columns. A cell holding 0 is open and a cell holding 1 is blocked. You start on the top-left cell and want to reach the bottom-right cell, stepping only on open cells. From a cell you may step to any of its 8 neighbors: up, down, left, right, or one of the four diagonals.

Return the number of cells on the shortest such path, counting the first and the last cell. Return -1 when there is no path, which includes the case where the start or the end cell is blocked. A 1 × 1 open grid is a path of one cell, so its answer is 1. You may change grid while you work.

Cells are written (row, column), counting from 0.

Example 1
Inputgrid = [[0, 1, 0], [0, 1, 0], [0, 0, 0]]Output4

Down to (1, 0), diagonally to (2, 1), then right to (2, 2). A path of 3 cells would need the center cell, which is blocked.

Example 2
Inputgrid = [[0, 0, 1], [1, 1, 1], [0, 0, 0]]Output-1

The middle row is blocked all the way across, and a diagonal step still has to land on an open cell.

Example 3
Inputgrid = [[1, 0], [0, 0]]Output-1

The start cell is blocked.

Constraints
  • 1 ≤ n ≤ 100

  • Every cell is 0 or 1.

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

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.

Step throughRot spreads from both ends
Step 1 of 78
Line 1 is about to run.
from collections import deque
def minutes_to_rot(shelf):
queue = deque()
fresh = 0
for i in range(len(shelf)):
if shelf[i] == 2:
queue.append(i)
elif shelf[i] == 1:
fresh += 1
minutes = 0
while 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] = 2
fresh -= 1
queue.append(j)
minutes += 1
return minutes if fresh == 0 else -1
Names
no names yet
Output
(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.

On paperRot 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.

minutes

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.

mediumBreadth-first searchQueues and deques target 25 min

Rotting oranges

A crate of oranges is a grid grid with rows rows and cols columns. Each cell is 0 (empty), 1 (a fresh orange) or 2 (a rotten orange). Rot spreads one step per minute: when a minute passes, every fresh orange with a rotten orange directly above, below, left or right of it turns rotten too. Rot does not cross corners or empty cells.

How many minutes pass before the crate holds no fresh orange? Return that number. Return 0 if the crate starts with no fresh orange, and -1 if some fresh orange can never rot. You may change grid while you work.

Cells are written (row, column), counting from 0.

Example 1
Inputgrid = [[0, 2, 1, 1], [1, 1, 0, 1], [1, 0, 0, 1]]Output4

Minute 1 rots (1, 1) and (0, 2). Minute 2: (1, 0) and (0, 3). Minute 3: (2, 0) and (1, 3). Minute 4: (2, 3), the last fresh orange.

Example 2
Inputgrid = [[2, 0, 1], [1, 0, 1]]Output-1

(1, 0) rots in minute 1, but the empty middle column cuts the two oranges on the right off from the rot.

Example 3
Inputgrid = [[2, 0, 2]]Output0

There is no fresh orange, so no time needs to pass.

Constraints
  • 1 ≤ rows, cols ≤ 200

  • Every cell is 0, 1 or 2.

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

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.

Step throughFewest presses from 2 to 9
Step 1 of 80
Line 1 is about to run.
from collections import deque
def fewest_presses(start, target):
queue = deque([(start, 0)])
visited = {start}
while queue:
x, presses = queue.popleft()
if x == target:
return presses
for candidate in (x + 1, x * 2):
if candidate <= target and candidate not in visited:
visited.add(candidate)
queue.append((candidate, presses + 1))
return -1
Names
no names yet
Output
(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 in orderMake the neighbors of a word

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.

Your program

Add lines from the list below, in order.

    Unused lines (some do not belong)
    • 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 + after
    • return 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.

    hardBreadth-first searchHash maps and sets target 40 min

    Word ladder

    You get a start word begin_word, a target word end_word and a list of allowed words word_list. All the words have the same length and use lowercase letters. A ladder goes from begin_word to end_word one word at a time, and each word differs from the word before it in exactly one position. begin_word may be missing from the list, but every later word on the ladder must come from it. The list may also hold a word twice, or hold begin_word.

    Count the words on the shortest ladder, with begin_word and end_word both included, and return that count. If no ladder exists, for example because end_word is not in the list, return 0.

    Example 1
    Inputbegin_word = "cat", end_word = "dog", word_list = ["cot", "cog", "dog", "cut", "dot"]Output4

    One shortest ladder is cat, cot, cog, dog. cat and dog differ in all three positions, and each step changes one letter, so no ladder can be shorter than 4 words.

    Example 2
    Inputbegin_word = "cold", end_word = "warm", word_list = ["cord", "card", "ward", "warm", "worm", "word"]Output5

    cold, cord, card, ward, warm. cold and warm differ in all four positions, so no ladder can be shorter than 5 words.

    Example 3
    Inputbegin_word = "lead", end_word = "gold", word_list = ["load", "goad", "goal"]Output0

    gold is not in the list, so no ladder can end there. lead, load, goad, gold would work if it were.

    Constraints
    • 1 ≤ length of each word ≤ 10

    • 1 ≤ len(word_list) ≤ 104

    • All words have the same length and only lowercase letters.

    • begin_word != end_word

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    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.

    Quick checkWhich question needs BFS

    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.

    Say itWhy BFS and not DFS

    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.

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.