Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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