Maze Solving

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.

One solution, 1681 pixels (enlarged)

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.

One solution, 4 megapixelsMultiple solutions, 3 megapixels
One solution, 16 megapixelsOne solution, 100 megapixels

One solution, 225 megapixels


# 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[0] == "-":
			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[1])
	if not os.path.exists(path):
		return "Could not resolve maze file '%s'." % args[1]

	# path to save result
	outpath = os.path.dirname(path) + "/" + os.path.split(args[1])[1].split(os.extsep, 1)[0] + "_solved.png"

	log("Loading maze...")

	# try to open the image
	try:
		img = Image.open(path)
	except:
		log("Failed to open maze file '%s'." % args[1])

	# 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[0], start[1]+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[0]+_[0], crawler[1]+_[1]
				if maze[y][x] == -1:
					maze[y][x] = maze[crawler[1]][crawler[0]]+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[0], start[1]+1)]
	#	for crawler in crawlers:
	#		if exit == crawler:
	#			break
	#		for _ in ((1, 0), (-1, 0), (0, 1), (0, -1)):
	#			x, y = crawler[0]+_[0], crawler[1]+_[1]
	#			if maze[y][x] == -1:
	#				maze[y][x] = maze[crawler[1]][crawler[0]]+1
	#				crawlers.append((x, y))

	# distance from exit to start
	n = maze[exit[1]][exit[0]]

	# current position while backtracking the shortest path
	p = (exit[0], exit[1]-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[1]+_[1]][p[0]+_[0]] == n:
				maze[p[1]+_[1]][p[0]+_[0]] = -2
				p = [p[0]+_[0], p[1]+_[1]]
				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[1]][exit[0]]
	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[0], start[1]] = (255, 0, 0)
	pix[start[0], start[1]+1] = (255, 0, 0)
	pix[exit[0], exit[1]] = (255, 0, 0)
	pix[exit[0], exit[1]-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[1], t, ("s", "")[t == 1])

# solve the maze
print solve()
Advertisements

4 thoughts on “Maze Solving

  1. I am not sure why but removing crawlers.remove(crawler) gives a better time than with it being there. could you explain why this happens?

    Like

    • You are totally correct. Without that line the code runs significantly faster. (By a factor of around two thirds in my tests!)

      	# ...
      	# crawl around the maze, marking each maze tile according to its shortest distance to the start
      	crawlers = [(start[0], start[1]+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[0]+_[0], crawler[1]+_[1]
      				if maze[y][x] == -1:
      					maze[y][x] = maze[crawler[1]][crawler[0]]+1
      					crawlers.append((x, y))
      	# ...

      What I think happens here is that I wrongly designed my while loop. I had in mind that the list crawlers contains all the path’s end points, gets processed by looking at each end point, does not reach the maze’s end, falls out of the for loop and goes back into the while loop.
      This strategy, however, does not work because the list Python is iterating through gets constantly bigger, whereby the added items are also part of the iteration. Because of this, what is left in the list (prior end points which are no longer at the path’s end) is not being looked at ever again, as the for loop gets eventually interrupted by the break statement. I assume that it is more resource intensive to remove from a list than it is to let things linger around.
      The faster code, not containing a while loop, would look like this.

      	# ...
      	# crawl around the maze, marking each maze tile according to its shortest distance to the start
      	crawlers = [(start[0], start[1]+1)]
      	for crawler in crawlers:
      		if crawler == exit:
      			break
      		for _ in ((1, 0), (-1, 0), (0, 1), (0, -1)):
      			x, y = crawler[0]+_[0], crawler[1]+_[1]
      			if maze[y][x] == -1:
      				maze[y][x] = maze[crawler[1]][crawler[0]]+1
      				crawlers.append((x, y))
      	# ...

      The only thing that bothers me is, that it does not seem elegant to iterate through a list and constantly append to it while doing so, although this is also what my code did, even if I did not intend it.
      Thanks for viewing my code, I greatly appreciate your efforts.

      Like

  2. I must say it is a fantastic approach, although resource intensive. I could go upto ‘perfect6k’ maze from Mike Pound’s examples (I have a 8 gig ram) which is not bad. I am looking at alternative data structures for the crawlers. appending and iterating through an array is not exactly a best time-utilization strategy. I shall let you know if anything comes up. Keep your good work on.

    Like

  3. Pingback: Second Anniversary – J-Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s