1. Concept library
  2. Data Structures & Algorithms
  3. Module 11: Graphs

Concept

Breadth-first search

BFS explores a graph level by level from a start node using a queue, visiting every node at distance d before any at d+1. In an unweighted graph the first time it reaches a node is along a shortest path.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain why BFS finds shortest paths in an unweighted graph
  2. Write BFS with a queue and a visited set
  3. Spot the bug of marking visited on dequeue

In practice

A few lines that show Breadth-first search doing its job.

Python
from collections import deque

def shortest_path_length(graph, start, goal):
    queue = deque([(start, 0)])
    seen = {start}
    while queue:
        node, dist = queue.popleft()
        if node == goal:
            return dist
        for nxt in graph[node]:
            if nxt not in seen:
                seen.add(nxt)          # mark when enqueued
                queue.append((nxt, dist + 1))
    return -1

The common mistake

Watch for

Marking a node visited when it is dequeued rather than when it is enqueued. The same node is queued many times, the work balloons, and on a grid the queue can grow to the square of what it should be.

What to know first

Your roadmap puts these before Breadth-first search, unless you already know them.

How it stays learned

Once a session shows you understand Breadth-first search, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled

Where it leads

Topics that build on Breadth-first search.

Previous in the module← Graph representations
Next in the moduleDepth-first search →