build-a-pathfinder / lesson-26.md
Lesson 26 · Maze generation

The perfect-maze property

The backtracker does not just make a maze, it makes a perfect one, exactly one path between any two cells. Today you verify that property directly by counting passages and checking full connectivity.

The goal

Verify a generated maze is perfect, N*M cells connected by exactly N*M-1 passages.

Start here - the target
TO DO
Scenario: A generated maze is perfect, a spanning tree of its cells
Givena 3 by 3 maze generated by the recursive backtracker from a generator seeded with 1
Whenits passages are counted and its cells are flooded from (0, 0) through carved passages
Thenit has 9 cells and exactly 8 passages (N*M-1)
Andthe flood reaches all 9 cells, so the maze is fully connected with no isolated rooms
Background

A maze generated this way is not just any maze, it is a perfect maze: there is exactly one path between any two cells, no loops and no walled-off regions. That is the same thing as saying the rooms and passages form a spanning tree of the grid, and trees have a crisp signature you can check with counting.

Two facts together prove it. First, a tree on N nodes has exactly N-1 edges, so a perfect maze of W*H rooms must have exactly W*H-1 passages, here 8 passages for 9 rooms. Second, it must be connected: a flood that steps only through carved passages, starting anywhere, must reach every room. Connected and one edge short of a cycle can only be a tree, so those two checks together certify perfection. This property is exactly what makes a maze’s solution unique, which the capstone leans on, and it holds for any generator that carves a spanning tree, including the second one you build next.

Make it work
// count passages: len(m.links)
// connectivity: BFS/flood over cells, stepping cell -> neighbor only
// when m.Linked(cell, neighbor); count how many cells are reached.
// perfect maze <=> passages == W*H-1 AND reached == W*H
// (a tree: connected, and one fewer edge than nodes means no cycle)
CheckpointDONE
You can confirm a maze is perfect, a spanning tree of its cells. Commit and stop here.