Prim's Algorithm is a minimum spanning tree algorithm adapted for maze generation. Unlike recursive backtracking, which dives deep into one corridor, Prim's grows the maze outward from its boundary ā like a crystal expanding in all directions. The result is a maze with shorter dead ends, more branching, and a natural, organic-looking structure favored by AAA game studios.
Prim's mazes look more like natural cave systems or garden hedgerows. The even expansion creates a balanced structure that's visually appealing. Our Hedge Maze garden game uses a Prim's variant specifically for this organic feel.
The shorter dead ends mean players spend less time backtracking from mistakes ā better for action games and multiplayer. The higher branching factor creates more decision points, increasing the maze complexity at intersections rather than in corridor length.
| Time Complexity | O(n log n) with priority queue, O(n²) with array |
| Space Complexity | O(n) ā frontier list can hold many walls |
| Perfect Maze? | ā Yes ā one path between any two cells |
| Corridor Style | Short passages with frequent branching |
| Dead-End Ratio | Higher than backtracking, but dead ends are shorter |
| Based On | Minimum spanning tree with randomized edge selection |
Experience Prim's organic structure in our Hedge Maze game, or compare it with recursive backtracking on the algorithm guide.
Recursive backtracking creates long, twisty corridors. Prim's creates shorter passages with more frequent branching. Backtracking feels "twisty"; Prim's feels "bushy" and more open.
It's a randomized adaptation. Classic Prim's MST picks the minimum-weight edge; the maze variant picks a random wall from the frontier. Both grow a tree one edge at a time.
Use Prim's for multiplayer games (less frustrating backtracking), exploration games (more decision points), or natural aesthetics. Use backtracking for puzzle games where long, challenging corridors are the goal.