Command Palette

Search for a command to run...

Module 21

Breadth-First Search

Explore in rings: the BFS template, fewest-steps shortest paths, grids, multi-source BFS, implicit graphs and 0-1 BFS.

Intermediate 4 lessons 7 problems ~45 min of lessons

Breadth-first search visits everything one step away, then everything two steps away, and so on. That order is exactly what you need for the fewest-steps question on an unweighted graph: the first time BFS reaches a node, it has found a shortest path to it.

This module turns that into one reusable template, then applies it to grids, to many starting points at once (rotting oranges, distance to the nearest zero), to graphs you never build explicitly (word ladders, combination locks), and to 0-1 weights with a deque.

Best after: Graph Fundamentals

Part 1

Learn the ideas

Part 2

Solve the problems

In order of difficulty. Each one shows the pattern it teaches.

  1. Multi-source BFS on a grid, counting levels as minutes.

  2. Single-source BFS on a grid with 8-directional moves.

  3. Multi-source BFS from every 0 gives each cell its distance to the nearest 0.

  4. BFS over states you generate on the fly, with forbidden states pre-marked as visited.

  5. Grid BFS with a goal test on the border (and the entrance excluded).

  6. An implicit graph of words, with neighbours generated by changing one letter at a time.

  7. 0-1 BFS: entering an empty cell costs 0, entering an obstacle costs 1.