Maze Generation Algorithms Explained

A random maze generator is a graph algorithm wearing a drawing. Once you see cells as vertices and passages as edges, the three workshop methods stop looking like magic and start looking like different ways to build a spanning tree. None of them is universally better. They bias texture: long runs, short branches, or a more uniform mix.

Mazes as graphs

List every legal cell. Connect two cells in the neighbor list only if they share a side (rectangle), a radial or circumferential border (polar), or a hex edge (axial coordinates). That neighbor list is the full possible graph. Generation deletes most of those potential edges until a maze remains. Walls are simply the unused neighbor relations.

Workshop rules: every cell has a unique identifier, passages are bidirectional, no self-loops, no duplicate edges, entrance and exit belong to the graph, and a path between them exists. Validation tests those invariants on many seeds.

Cells, edges, and spanning trees

A spanning tree of N vertices uses N − 1 edges, touches every vertex, and contains no cycles. Perfect mazes are spanning trees of the cell graph. Then there is exactly one simple path between any two cells. That is convenient for puzzle books and for proving that a drawing is not a disconnected scribble.

Perfect mazes versus looped mazes

Rectangular, circular, and hexagonal modes in Maze Foundry generate perfect mazes. Braided mode starts from a perfect maze and opens extra walls at selected dead ends. Room-and-corridor mode opens whole rectangles, then carves corridors, then adds doors. Those two modes stay connected and solvable, but independent cycles equal E − V + 1 and should not be advertised as zero.

Randomized depth-first search

Also called recursive backtracking. The workshop uses an iterative stack so a large grid cannot overflow the call stack. Pick a start cell, mark it visited, and while the stack is not empty look at unvisited neighbors of the top cell. If one exists, pick it with the seeded generator, open the wall, mark visited, and push. If none exist, pop. When every reachable cell is visited, you have a tree.

This walk often produces long winding corridors because the explorer prefers to continue rather than branch. That is a tendency, not a guarantee. A seed can still create a bushy DFS maze.

Randomized Prim

Mark one cell as inside the maze and collect frontier edges that touch an outside cell. Repeatedly pick a frontier edge at random. If it joins inside to outside, open it, mark the new cell inside, and add its frontier edges. Discard edges whose both ends are already inside so you do not create cycles in perfect mode. Prim can look more branched, with shorter corridors, depending on the graph and the random choices.

Randomized Kruskal

List every neighboring pair once. Put each cell in its own disjoint set. Shuffle the edge list with the seeded generator. Process edges in that order: connect the two cells only when find() reports different roots, then union them with path compression and union by rank. Stop when the graph is a spanning tree. Kruskal does not walk like a person; it sprinkles passages in shuffled order, which often yields a different visual rhythm than DFS.

Seeded random generation

Seeds are hashed (FNV-style, mixed with generator version 1) into a Mulberry32 stream. Shuffle, pick, and integer draws all read that stream. Math.random is not used for structural decisions. The generator is not a cryptographic source. Reproducibility means: same seed, type, dimensions, algorithm, structural settings, and version produce the same edges. Changing wall color must not change the puzzle. See version 1 documented in the workshop export notes.

Loops and braided mazes

After a perfect maze exists, list cells of degree one. For each, with probability equal to braiding strength, open one remaining neighbor wall if any unused neighbor exists. Strength 100% does not promise zero dead ends. Cycle count is computed from the graph, not estimated from how loopy the picture feels.

Worked graph example

Six cells in two rows: A B C / D E F. Neighbor edges: A-B, B-C, A-D, B-E, C-F, D-E, E-F.

Kruskal shuffle might try B-E, A-B, E-F, C-F, B-C, A-D, D-E.

Accept B-E (sets merge). Accept A-B. Accept E-F. Accept C-F. Skip B-C if B and C already share a set through F. Accept A-D if needed to bring D in, skip D-E if that would cycle. Final: 6 vertices, 5 edges, connected, acyclic.

DFS from A might visit A-B-C-F-E-D, opening a long snake. Same cells, different texture.

Run the live steps on the algorithm demonstrations. Generate matching full-size puzzles with the maze generator. Polar and hex graphs use the same three algorithms; only the neighbor function changes.

A second example: braid the six-cell tree by opening D-E after D is a dead end. Now E = 6, V = 6, cycles = 1. BFS from A to C may now have two routes of different lengths; the shortest is what the solver reports. DFS might still find the long way first. That is why the workshop refuses to say DFS always finds shortest paths in mazes with loops.

Differences in maze structure

Compare statistics after each algorithm: dead ends, junctions (degree ≥ 3), shortest solution length, and solution coverage. DFS often raises solution length. Prim may raise junction count. Kruskal sits between them on many rectangular seeds, but polar doubling of outer sectors changes branching in ways a square grid never will. Measure the graph in front of you rather than repeating a slogan about which method is “best”.

FAQ

Why iterative DFS instead of recursive?
Large 80 × 80 grids can exceed typical JavaScript call-stack limits. An explicit stack is the same algorithm with bounded native recursion.
Does Prim here match textbook Prim on weights?
It is the common maze adaptation: random frontier edges on an unweighted cell graph, not a heap of numeric weights.
Can Kruskal create cycles?
Not in perfect mode, because union is refused when find() matches.

Continue with how solvers reconstruct shortest paths.