Skip to content

Instantly share code, notes, and snippets.

@Deathnerd
Created October 11, 2014 05:18
Show Gist options
  • Save Deathnerd/bb9fa3cacf0824fe677c to your computer and use it in GitHub Desktop.
Save Deathnerd/bb9fa3cacf0824fe677c to your computer and use it in GitHub Desktop.
A recursive maze solver for python. It works but has one little bug... It returns false even if it solves the maze
__author__ = 'Deathnerd'
maze_string_list = ("1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1",
"1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 1",
"1 1 1 0 1 0 1 1 1 1 1 1 1 0 1 1 1 0 1 0 1",
"1 0 0 0 1 0 0 0 0 0 1 0 0 0 1 0 0 0 1 0 1",
"1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 0 1",
"1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1",
"1 1 1 0 1 1 1 0 1 1 1 1 1 0 1 1 1 0 1 1 1",
"1 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 1",
"1 0 1 0 1 1 1 0 1 1 1 0 1 0 1 1 1 0 1 1 1",
"1 0 1 0 0 0 1 0 0 0 1 0 1 0 1 0 1 0 1 0 1",
"1 0 1 1 1 1 1 0 1 1 1 0 1 0 1 0 1 1 1 0 1",
"1 0 1 0 1 0 0 0 0 0 1 0 1 0 0 0 0 0 1 0 1",
"1 1 1 0 1 0 1 1 1 1 1 0 1 0 1 0 1 1 1 0 1",
"1 0 0 0 1 0 0 0 1 0 0 0 1 0 1 0 1 0 0 0 1",
"1 0 1 0 1 0 1 1 1 0 1 1 1 1 1 0 1 0 1 0 1",
"1 0 1 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 1 0 1",
"1 0 1 1 1 1 1 0 1 1 1 1 1 0 1 1 1 0 1 1 1",
"1 0 0 0 0 0 0 0 1 0 0 0 1 0 1 0 0 0 1 0 1",
"1 1 1 1 1 0 1 0 1 0 1 1 1 0 1 1 1 0 1 0 1",
"1 0 0 0 0 0 1 0 0 0 0 0 1 0 1 0 0 0 0 0 1",
"1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1")
maze = []
m = []
i = 0
for row in maze_string_list:
maze.append(list(map(int, maze_string_list[i].split(" "))))
i += 1
__author__ = 'Deathnerd'
"""
It works.... somewhat. Returns false even though it solves it
"""
from maze import maze
import msvcrt as m # Only works in windows
def wait():
m.getch()
def print_maze():
for x in maze:
print x
print "\n"
def solve():
return _solver(maze[0].index(0), 0)
def _solver(x_position, y_position):
print_maze()
wait() # Uncomment this to wait for user input on each iteration
maze[y_position][x_position] = 2 # mark as visited
if y_position == maze.__len__() - 1:
return True
# move down
down_position = maze[y_position + 1][x_position]
if down_position is not 1 and down_position is not 2:
_solver(x_position, y_position + 1)
# move up
up_position = maze[y_position - 1][x_position]
if y_position is not 0 and up_position is not 1 and up_position is not 2:
_solver(x_position, y_position - 1)
# move left
left_position = maze[y_position][x_position - 1]
if x_position is not 0 and left_position is not 1 and left_position is not 2:
_solver(x_position - 1, y_position)
# move right
right_position = maze[y_position][x_position + 1]
if x_position is not maze[0].__len__() - 1 and right_position is not 1 and right_position is not 2:
_solver(x_position + 1, y_position)
# everything failed. Mark it as a failure
maze[y_position][x_position] = 0
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment