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).
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
# This Python program takes in a maze as png and solves for the shortest path solving it. # The maze should have a border all around with two holes at the top and bottom indicating start and end. # The red line indicates the solved path, whereas the different hues of blue indicate that tile's distance to the start (used to determine shortest path) # Usage: python maze.py <maze file> # inspired by this YouTube video # * https://www.youtube.com/watch?v=rop0W4QDOUI # download different mazes (Mike Pound's GitHub repository) # * wget https://raw.githubusercontent.com/mikepound/mazesolving/master/examples/normal.png # import from PIL import Image import os, sys, time # solve the maze def solve(): # start timer t0 = time.time() # get arguments args = sys.argv # flags silent = False # parse flags for arg in args: if arg == "-": args.remove(arg) if arg in ("-h", "--help"): return "\n".join(( " usage: python maze.py <maze file>", "", " -h, --help : display this help info", " -s, --silent: silence not vital output" )) elif arg in ("-s", "--silent"): silent = True # print not vital information def log(msg): if not silent: print msg # there needs to be a maze file specified if len(args) < 2: return "Please specify a maze file." # the maze file must exist path = os.path.abspath(args) if not os.path.exists(path): return "Could not resolve maze file '%s'." % args # path to save result outpath = os.path.dirname(path) + "/" + os.path.split(args).split(os.extsep, 1) + "_solved.png" log("Loading maze...") # try to open the image try: img = Image.open(path) except: log("Failed to open maze file '%s'." % args) # image dimensions and pixels w, h = img.size pix = img.load() # define what counts as a wall wall = pix[0, 0] # load the maze png into memory maze = [[(None, -1)[pix[x, y] != wall] for x in range(w)] for y in range(h)] # get start and exit start, exit = None, None for x in range(w): if pix[x, 0] != wall: start = (x, 0) if pix[x, h-1] != wall: exit = (x, h-1) # start and exit must exit if start is None: return "Specified maze does not contain a start." if exit is None: return "Specified maze does not contain an exit." log("Solving...") # The original code segment for crawling through the maze is used here. # crawl around the maze, marking each maze tile according to its shortest distance to the start crawlers = [(start, start+1)] while exit not in crawlers: for crawler in crawlers: if crawler == exit: break crawlers.remove(crawler) for _ in ((1, 0), (-1, 0), (0, 1), (0, -1)): x, y = crawler+_, crawler+_ if maze[y][x] == -1: maze[y][x] = maze[crawler][crawler]+1 crawlers.append((x, y)) # However, a reader mentioned, the code ran faster, if the line 'crawlers.remove(crawler)' had been removed. # Being notified of this speed increase regarding this essential code segment, I slightly rewrote it. # The code still crawls around the maze and labels tiles, though faster. # # # crawl around the maze, marking each maze tile according to its shortest distance to the start # crawlers = [(start, start+1)] # for crawler in crawlers: # if exit == crawler: # break # for _ in ((1, 0), (-1, 0), (0, 1), (0, -1)): # x, y = crawler+_, crawler+_ # if maze[y][x] == -1: # maze[y][x] = maze[crawler][crawler]+1 # crawlers.append((x, y)) # distance from exit to start n = maze[exit][exit] # current position while backtracking the shortest path p = (exit, exit-1) # backtrack until the start is reached while n > 0: n -= 1 for _ in ((1, 0), (-1, 0), (0, 1), (0, -1)): if maze[p+_][p+_] == n: maze[p+_][p+_] = -2 p = [p+_, p+_] break # save the image log("Saving image...") img = Image.new("RGB", (w, h)) pix = img.load() # path's length used to determine tile's hues l = maze[exit][exit] for y in range(h): for x in range(w): # tile part of the solved path if maze[y][x] == -2: pix[x, y] = (255, 0, 0) # tile not considered part of the maze path elif maze[y][x] == -1: pix[x, y] = (255, 255, 255) # tile considered, yet not part of solved path elif maze[y][x] is not None: pix[x, y] = (50, 0, 255*maze[y][x]/l) # all other tiles are walls, which stay black # fancify start and end pix[start, start] = (255, 0, 0) pix[start, start+1] = (255, 0, 0) pix[exit, exit] = (255, 0, 0) pix[exit, exit-1] = (255, 0, 0) # save image to disk try: img.save(outpath, "PNG") except: return "Failed to save solved maze as '%s'." % outpath # print status t = time.time()-t0 return "Solved maze '%s' in %f second%s." % (args, t, ("s", "")[t == 1]) # solve the maze print solve()