Skip to content
All posts

Engineering · 7 May 2026 · 6 min read

What I Learned Building a Maze Generator and Solver From Scratch

No libraries. No game engine. Just a canvas, a stack, and a priority queue.

There’s a category of project that sits in an uncomfortable middle ground too complex to finish in an afternoon, not complex enough to justify a framework. A maze generator with a built-in A* solver is exactly that kind of project. I built one recently using nothing but vanilla JavaScript and the Canvas 2D API, and the gaps it exposed in my understanding were more valuable than anything I could have learned from a tutorial.

Here’s what actually surprised me.

The generation algorithm is deceptively simple, until it isn’t

I went with recursive backtracking (also called depth-first search maze generation). The idea sounds trivial:

  1. Start at cell (0, 0).
  2. Pick a random unvisited neighbour, knock down the wall between you, move in.
  3. If you’re boxed in, backtrack until you find a cell with unvisited neighbours.
  4. Repeat until every cell has been visited.

This produces a perfect maze - exactly one path between any two cells. No loops, no isolated regions, no shortcuts. Guaranteed.

The part that caught me off guard was how to represent walls efficiently. My first instinct was a separate 2D array of wall objects. That works, but you end up managing two data structures that have to stay in sync. The cleaner approach: give each cell four boolean flags (top, right, bottom, left). When you carve a passage from cell A to cell B, you clear A's right flag and B's left flag in the same operation. One source of truth, no sync required.

// Carving east from (r, c) into (r, c+1)
cells[r][c].right = false;
cells[r][c + 1].left = false;

Simple when you see it. Non-obvious before you do.

Animation forced me to think about iteration differently

My initial implementation used actual recursion. It worked perfectly — and immediately stack-overflowed on a 41×41 grid (1,681 cells, worst-case recursion depth of 1,681 frames). The fix was converting to an explicit stack and pulling one step per animation frame via requestAnimationFrame.

This is a broader lesson that applies to any animated algorithm: you cannot let the algorithm run to completion in a single synchronous call if you want to visualise it. Every recursive algorithm you want to animate needs to be refactored into an iterative state machine where each requestAnimationFrame callback advances the state by one (or N) steps and then yields back to the browser.

function carve() {
if (stack.length === 0) { done(); return; }

const [r, c] = stack[stack.length — 1];
// … pick neighbour, carve wall …

animId = requestAnimationFrame(carve);
}

The tradeoff with stepsPerFrame is real. At 1 step per frame on a 41×41 maze, generation takes ~28 seconds at 60fps. At 50 steps per frame, it's under a second. Exposing this as a slider makes the algorithm's complexity tangible in a way a static benchmark never could.

A* is not as intimidating as it looks

I had read about A* many times. I had never actually implemented it. The mental model that finally made it click:

A* is BFS, but instead of exploring cells in order of discovery, it explores them in order of estimated total cost_._

The total cost estimate for a cell is f = g + h:

  • g = the actual number of steps taken to reach this cell from the start
  • h = the heuristic estimate of steps remaining to the goal (Manhattan distance for a grid)

At every step, pop the cell with the lowest f from the open list, expand its passable neighbours, and update their g and f scores if you've found a cheaper route. Stop when you pop the goal cell.

The part the textbooks gloss over: the open list needs to stay sorted by f. For a maze of this scale, I used a plain array with Array.sort() before each pop. This is O(n log n) per step — inefficient for large graphs, but fine for a maze under 2,000 cells. A proper implementation would use a binary min-heap, which gives O(log n) insertion and O(log n) pop.

The heuristic choice matters more than I expected. Manhattan distance (|r1 - r2| + |c1 - c2|) is admissible — it never overestimates — which guarantees the path A* finds is optimal. If you use Euclidean distance instead, you get a slightly different search pattern that still works but feels less "snappy" on a grid where only cardinal movement is allowed.

The efficiency metric revealed something counterintuitive

I added a stat: efficiency = path_length / cells_explored. I expected it to hover around 50–70% for most mazes. What I actually saw:

  • Small mazes (15×15): efficiency often 70–90%
  • Large mazes (41×41): efficiency often 30–50%

At first this felt wrong — shouldn’t A* get better with more space to work with? The issue is maze structure, not maze size. Recursive backtracking produces mazes with long, winding corridors and relatively few decision points. On a large maze, A* often has to explore deep dead-end corridors before finding the right branch, because the heuristic can’t see through walls. The maze topology defeats the heuristic.

This is the kind of insight you only get from building the thing and watching it run.

Canvas rendering is fast until you make it slow

My first rendering pass called clearRect and redrew every cell wall on every animation frame. At 15×15 this was fine. At 41×41 with 1,681 cells and up to 4 wall segments each, that's ~6,700 line draw calls per frame. Still fine at 60fps — but add the A* visualisation (filling explored cells and the path on every frame) and you start feeling it.

The fix I landed on was draw order:

  1. Fill the background.
  2. Fill explored cells (bulk fillRect pass).
  3. Fill the path cells (another bulk pass).
  4. Draw start and end markers.
  5. Draw all walls last, on top of everything.

Walls drawn last means they always appear clean regardless of what’s underneath. This avoids the artefacts you get when fill operations partially cover wall lines. It’s the same painter’s algorithm principle that applies to any layered 2D rendering.

What I’d do differently

Use an OffscreenCanvas for the static maze. Once generation is complete, the maze walls never change. Redrawing them every frame during A* is wasteful. The right approach is to render the completed maze once to an OffscreenCanvas, then composite it with the animated layers on each frame. I didn't implement this, but it's the obvious next step for performance at larger sizes.

A proper priority queue. The Array.sort() approach works but it's the kind of technical debt that becomes noticeable the moment you push toward 100×100 grids. A binary heap implementation is ~40 lines of JavaScript and drops per-step complexity from O(n log n) to O(log n).

Dijkstra for comparison. Adding a second solver that uses Dijkstra (essentially A* with h = 0) side by side would make the value of the heuristic visible. You'd see Dijkstra explore the entire reachable maze while A* homes in on the goal. That delta is the entire argument for informed search.

The real takeaway

The maze project forced me to think carefully about data structure design, algorithm-to-animation conversion, rendering pipeline order, and heuristic admissibility — none of which come up when you’re building CRUD apps. These are the muscles that make you faster at everything else.

If you’re looking for a project that sits in the productive discomfort zone between “too easy” and “I need a PhD,” this is a good one.

The full source is a single index.html file — no build step, no dependencies.

Built with: vanilla JavaScript, Canvas 2D API, requestAnimationFrame. Algorithms: recursive backtracking (generation), A with Manhattan heuristic (solver).*

  • #software-engineering
  • #canvas-2d
  • #maze
Also on Medium ↗