Skip to content

Instantly share code, notes, and snippets.

@vatsalparekh
Created April 16, 2017 19:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vatsalparekh/acbd8a2a231988499c79bcbf50a363ed to your computer and use it in GitHub Desktop.
Save vatsalparekh/acbd8a2a231988499c79bcbf50a363ed to your computer and use it in GitHub Desktop.
Recursive maze solver in Python
from tabulate import tabulate
maze = [['_', '_', '#', '_', '#'],
['_', '#', '_', '_', '_'],
['_', '#', '_', '#', '_'],
['_', '_', '_', '_', '_'],
['#', '#', '#', '_', 'G']
]
maze_x = len(maze) - 1
maze_y = len(maze[0]) - 1
def move(x, y):
if not (0 <= x <= maze_x and 0 <= y <= maze_y): # if outside of maze
return False
if maze[y][x] == '#': # if wall
return False
if maze[y][x] == '@': # already visited
return False
if maze[y][x] == 'G': # if the solution
return True
maze[y][x] = '@'
if move(x + 1, y): # East
return True
if move(x, y + 1): # South
return True
if move(x - 1, y): # West
return True
if move(x, y - 1): # North
return True
maze[y][x] = '_'
return False
if __name__ == '__main__':
move(0, 0)
print(tabulate(maze))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment