Courses / DSA Patterns for Working Engineers / Chapter 34
Module 11 · Graph algorithms · Chapter 34 of 39
State-Space BFS: Fewest Moves Through Puzzle States
Builds on Graphs: Modelling, Breadth-First and Depth-First Search. Next up: Grids as Graphs: Flood Fill, Islands and Spreading.
Part 1 · Introduction to state-space BFS
Puzzles that are graphs in disguise
A combination lock, a sliding-tile toy and a jug that must end up holding exactly four litres look nothing like a metro map. Each is still a graph, and "what is the fewest number of moves?" is a shortest-path question.
A state is a complete description of the puzzle at one moment: the digits showing on a lock, the arrangement of the tiles, the litres in each jug. A move turns one state into another, and a goal is a state, or a test on a state, that ends the search. Take states as nodes and moves as edges, and the puzzle becomes a graph called the state space. The graphs chapter ran breadth-first search on graphs you are handed. Here nobody hands you the graph. It is implicit: you never build it. You write a function that lists the neighbours of a state, and the search discovers the graph as it walks. Three things define any such puzzle: the start state, that function, and a test for the goal.
| Puzzle | State | One move | Goal |
|---|---|---|---|
| Combination lock | the digits showing | turn one wheel one step |