Draw Maze

Draw Maze

Draw something, and you get a maze whose one route from entrance to exit traces your drawing. It works by choosing the route first and building the rest of the maze around it.

These mazes have no loops. Every cell can be reached, and between any two cells there's exactly one route that never doubles back. A network like that, where corridors branch but never join back up, is called a tree. Here's a small maze made by the same code, with the route between two random cells lighting up. Whichever two cells you pick, there's only one way between them.

So the route from entrance to exit can be decided before anything else. Carve that route, then let corridors grow off it into the empty cells, one cell at a time, never into a cell that's already connected. Nothing joins back up, so the result is still a tree, and the route you started with is still the only way through.

amber is the route; dark squares are cells no corridor has reached yet

The route can't cross itself, and a drawing can be any shape, so the route can't just follow your strokes. Instead it's built in three steps:

  1. Chop the grid into 2×2 blocks and mark every block your drawing touches.
  2. Plan a route through the blocks, from the left wall to the right wall, never visiting a block twice. It heads for the nearest mark, takes the longest run it can find through it, then heads for the next, with short wandering corridors in between.
  3. Walk the route cell by cell, zigzagging through all four cells of each block. Whichever side the route comes into a block from and leaves by, there's always a way to visit all four cells and leave on the right side. Now every drawn cell is on the path.
  4. Shuffle the path's shape. A zigzag that regular would stand out in the finished maze, so the path gets thousands of small edits, each of which keeps both ends where they are and never drops a drawn cell: where the path passes the same way along two neighboring cells, reconnect them crosswise and walk the stretch between backwards; push a step out sideways into two free cells beside the drawing; or pull such a bump back in.

 

The path doesn't trace your strokes in order; it just passes through every cell you drew on, plus a few beside them, and winds like any other corridor, so you can't spot it before you solve it. Where a letter forks, like the crossbar of an A, the route in step 2 can't take both branches, so the leftover branch gets its own visit if a short corridor reaches it, and the shuffle picks up any drawn cells that are still missing right next to the path.

A link carries only the grid size, a random seed and your strokes. Opening it runs all of the above again and gets the same maze.