Created
April 16, 2017 19:16
-
-
Save vatsalparekh/acbd8a2a231988499c79bcbf50a363ed to your computer and use it in GitHub Desktop.
Recursive maze solver in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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