← Back to Hub

Recursive Backtracker (Perfect Maze)

The Concept

Imagine a miner digging tunnels. They choose a random unvisited neighbor, carve a path, and move there. If they hit a dead end (all neighbors visited), they backtrack along their path until they find a new opening.

Result: A "perfect" maze with no loops and every cell reachable.

Core Logic


function step(current) {
    current.visited = true;
    let next = getRandomUnvisitedNeighbor(current);
    
    if (next) {
        stack.push(current);
        removeWalls(current, next);
        step(next);
    } else if (stack.length > 0) {
        step(stack.pop());
    }
}