Skip to content
CodeItRaw
Graphs

Lesson 4/4

Depth-first search finds a way, not the shortest one. For the shortest you change the order: first all neighbours of the start, then their neighbours. You spread outward like rings from a stone dropped in water; the first time you reach a node you have reached it in the fewest steps. This is breadth-first search (BFS).

from collections import deque
queue = deque([(start, 0)])
seen = {start}
while queue:
node, steps = queue.popleft()
if node == goal:
return steps
for nxt in graph[node]:
if nxt not in seen:
seen.add(nxt)
queue.append((nxt, steps + 1))
return -1
The only difference from DFS is a queue in place of the stack: first in, first out. The step count travels in the queue with the node. If the queue empties and the goal never came out, there is no way to it.

This holds where every step costs the same (one square on a grid, one move in a maze). With limited energy, or when looking for the nearest target, the distance as the crow flies misleads you: a near target behind a wall can cost more than a far one in the open. Measure the distance with BFS.

Tasks

Tasks open in order. Solve them all and the next lesson opens.

This lesson's tasks open when the lessons before it are finished. You can read the explanation now.

  1. 01

    Fewest Steps

    Function

  2. 02

    The Vault

    Infiltration

If you would rather not wait for the order, every problem is open without locks: Problem list