Mazes have been a subject of human interest for thousands of years. The Greeks used them to trap a bull-man hybrid, the French built them to show how they could impose order on nature, and even nowadays people enjoy wandering around corn mazes.
The algorithmic art of using computers to solve mazes — and even to find the shortest path through a maze –, however, has only emerged in the last couple of decades.
I was inspired by a recent Computerphile video in which Michael Pound talks about implementing different path finding algorithms for use in maze solving. And as he used Python — one of my favourite languages out there –, I thought I could give it a try and came up with this maze solver.
The mazes given to the solver (through a .png file) have to have a specific form. The maze needs to have a border all around (painted black) with two holes at the top and bottom, marking the maze’s start and exit (all path pixels are white).
Then the solver — using PIL — reads in the maze file, determines start and exit and starts at the maze’s start, labelling each maze path according to its shortest distance to the start. After it has found the exit, it stops looking at the maze and traces its origins back from the exit, marking the path it goes along as the maze’s optimal solution (highlighted in red).
The different hues of blue indicate the tile’s distance to the start, the white tiles are tiles the solver did not even look at.
The different shadings also reveal information about the maze. Mazes with only one solution tend to have sharp changes as there are parts of the maze separated by only one wall, yet separated by a huge walk distance through the maze. The one maze with multiple solutions (see upper right image below) — in contrast — has only gradual changes in hue.
To solve a 4 megapixel maze, the solver takes around 3 seconds, for a 16 megapixel maze around 14 seconds and for a 225 megapixel maze around 7 minutes and 22 seconds.
Performance was measured on an Intel Core i7 (4.00 GHz).
All mazes shown were downloaded from Michael Pound’s mazesolving GitHub repository, which were mostly generated using Daedalus.
The solver’s source code is listed below, though you can also download the .py file.
# Python 2.7.7 Code
# Jonathan Frech, 25th of Feburary 2017
# edited 26th of February 2017
# edited 27th of February 2017
# edited 22nd of March 2017
# edited 29th of March 2017