Maze generation algorithms explained

A computer can draw a fresh maze in a blink, and there are many ways to do it. Each classic algorithm follows its own simple rule, and each leaves a fingerprint in the result: long rivers or bushy dead ends, straight corridors along the edges or boxy rooms. This page explains what a maze is in the language of graphs, how eleven well-known generators work, how to measure the texture they leave, and how a maze is solved.

Two mazes growing from the same seed: the recursive backtracker on top with its orange stack winding back to where the search began, and randomized Prim's below with the orange cells of its frontier at the edge of the blue maze, each with a green start and a red exit

A maze is a spanning tree

Draw a dot in the middle of every cell of a grid and a line between every pair of neighbouring cells: that is the grid graph, with C·R nodes for C columns and R rows. A maze opens some of those lines as passages and keeps the rest as walls. A perfect maze has exactly one path between any two cells, with no loops and no closed-off parts, which is exactly the definition of a spanning tree: a set of edges that connects all nodes without a cycle. Every spanning tree of n nodes has n − 1 edges, so a perfect maze of 20 × 12 cells always has 239 passages, however it was made. A grid has an astronomical number of spanning trees, and a maze generator is a random rule for picking one of them.

The recursive backtracker and the growing tree

The recursive backtracker is a randomized depth-first search. Start in any cell; while the current cell has unvisited neighbours, knock down the wall to a random one and move there, pushing it on a stack; when there is none, pop the stack and back up until a cell with unvisited neighbours turns up. Every cell is pushed and popped once, so it takes about 2n steps. The search runs as far as it can before it turns, so the maze has long, winding passages and only about 10 % dead ends. The growing tree generalises it: keep a list of active cells and carve from one of them; always taking the newest gives the backtracker, taking a random one behaves like Prim's, and mixing the two rules mixes the textures.

Prim's and Kruskal's: minimum spanning trees with random weights

Prim's and Kruskal's algorithms find minimum spanning trees of weighted graphs; given random weights they produce random mazes. The randomized Prim's used here keeps a frontier of cells next to the maze and joins a random frontier cell to a random maze neighbour, so the maze grows outwards from its seed like a crystal and is full of short dead ends, about 35 % of the cells. Kruskal's takes all walls in random order and knocks one down whenever the cells on its two sides belong to different sets, then merges the sets; a union-find structure with path compression answers that question in nearly constant time. Walls between cells of the same set are skipped, because opening them would make a loop.

Random walks: Aldous–Broder and Wilson's algorithm

Aldous–Broder (found independently by David Aldous and Andrei Broder around 1989) walks at random from neighbour to neighbour over the whole grid and carves a passage whenever it enters a cell for the first time. It is simple and beautiful: the result is a uniform spanning tree, every possible perfect maze with the same probability. But the last few unvisited cells take a long time to find, so it needs many more steps than cells. David Wilson's algorithm (1996) gives the same distribution much faster: start from a cell not yet in the maze and walk at random until the walk hits the maze, erasing every loop the walk makes on the way; the loop-erased path is then added as a passage. Uniform spanning trees have a known texture: on a large grid 8/π²·(1 − 2/π) ≈ 29.45 % of the cells are dead ends.

Hunt-and-kill, the binary tree and sidewinder

Hunt-and-kill walks like the backtracker but, when it is stuck, does not back up: it scans the grid row by row for an unvisited cell next to the maze, joins it and walks on from there. Its mazes look like the backtracker's, with long rivers. The binary tree is the simplest algorithm of all: every cell opens a passage either north or east at random. It needs no memory, but its bias is plain to see: the top row and the right column become straight corridors, and from every cell there is a path that only goes up and right, so the maze is a binary tree rooted in the top right corner. Sidewinder works row by row: it carves a run of cells eastwards and, at random moments, closes the run by opening one of its cells to the north. The top row is one long corridor and paths never double back downwards.

Eller's algorithm and recursive division

Marlin Eller's algorithm (1982) builds a perfect maze of any height while keeping only one row in memory. Every cell of the current row belongs to a set; neighbours in different sets are joined at random and their sets merged, then every set sends at least one passage down into the next row, so nothing is cut off; the last row joins all remaining sets. That makes it ideal for mazes that scroll forever. Recursive division works the other way round: start with one open room, build a wall across it with a single gap, and divide each of the two chambers again until they are one cell wide. It adds walls instead of carving passages, needs only about one step per chamber, and its mazes show long straight walls and a boxy, room-like structure.

Measuring texture: dead ends, rivers and corridors

Walter Pullen's maze classification calls the character of a maze its texture, and it can be measured. Dead ends are cells with a single opening; their share runs from about 10 % for the backtracker to 35 % for Prim's. The longest path is the tree's diameter, found with two breadth-first searches: from any cell to the farthest one, and from there to the farthest again. The app computes the average corridor length as passages per branch: the cells that are not plain corridor cells (junctions and dead ends) split the tree into branches, so the mean branch has (n − 1) / (k − 1) passages. Its river value is the average length of the dead-end branches, counted from each dead end back to its junction: high when dead ends are long rivers, low when they are short stubs. The solution length is the distance from the start to the exit.

Solving a maze

Breadth-first search uses a queue to visit the cells in rings of equal distance from the start: the start, then every cell one step away, then two steps, and so on. Each cell stores its distance, which the app paints from purple to yellow, and stepping back from the exit to a neighbour one closer each time traces the shortest path; in a perfect maze it is the only path. A* search explores the cell with the smallest f = g + h first, where g is the number of steps so far and h the Manhattan distance to the exit, a heuristic that never overestimates on a grid, so the path it finds is still the shortest while it usually opens far fewer cells. Dead-end filling needs no search: fill every dead end, keep filling the cells that become dead ends, and the unfilled corridor is the solution. A walker inside a maze can always escape a perfect maze by keeping one hand on the wall. To try that yourself, play the PictorX maze game.

Поширені запитання

Why does the recursive backtracker make so few dead ends?

Because it always goes on from the newest cell. It keeps walking into unvisited cells as long as it can, so every branch is as long as possible before the search has to back up, and a dead end only appears where the walk got completely stuck. Algorithms that pick a random cell to grow from, like Prim's, start new branches everywhere, and most of those branches end after a cell or two.

How many steps does each algorithm take?

The binary tree, sidewinder, Prim's and Kruskal's carve one passage per cell, about n steps for n cells (Kruskal's also inspects walls it rejects). The backtracker and the growing tree push and pop every cell, about 2n. Hunt-and-kill adds its row scans and Eller's one step per row. Recursive division adds one wall per chamber, fewer steps than cells. The random walks are slower: Wilson's needs several times n steps and Aldous–Broder many more, since its cover time on a grid grows like n·(log n)². The texture table counts the steps for the same grid.

Are these mazes the same as minimum spanning trees?

Randomized Prim's and Kruskal's are the classic minimum spanning tree algorithms run on a grid whose edges have random weights (or are taken in random order), so their mazes are minimum spanning trees of those random weights. That does not make them uniformly random: Prim's in particular favours bushy trees. Only Wilson's algorithm and Aldous–Broder pick every spanning tree with the same probability.

How can a maze have loops or rooms?

Perfect mazes have neither, but they are easy to add: knocking down a few extra walls after generation creates loops (a braid maze has no dead ends at all), and stopping recursive division before the chambers are one cell wide leaves open rooms. With loops, there can be several paths to the exit, and the wall-following trick can fail when the exit lies inside a loop, while breadth-first search still finds the shortest way.

Готові спробувати?

Відкрийте PictorX у браузері — без встановлення і без кредитної картки.

Open the maze generation app