Created
February 23, 2020 03:27
-
-
Save ronhuang/c5991bc587fae23cb3bfbc5093280cd4 to your computer and use it in GitHub Desktop.
Simple maze solver
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
import sys | |
from collections import namedtuple | |
Point = namedtuple('Point', ['x', 'y']) | |
WIDTH = int(sys.argv[1]) | |
HEIGHT = int(sys.argv[2]) | |
START = Point(int(sys.argv[3]), int(sys.argv[4])) | |
END = Point(int(sys.argv[5]), int(sys.argv[6])) | |
visited = [False] * WIDTH * HEIGHT | |
path = [] | |
def push(p): | |
path.append(p) | |
visited[p.x + p.y * WIDTH] = True | |
def pop(): | |
p = path.pop() | |
visited[p.x + p.y * WIDTH] = False | |
return p | |
def go(p): | |
# out of bound | |
if p.x < 0 or p.x >= WIDTH: | |
return False | |
if p.y < 0 or p.y >= HEIGHT: | |
return False | |
# already visited? | |
if visited[p.x + p.y * WIDTH]: | |
return False | |
push(p) | |
if p == END: | |
if all(visited): | |
return True | |
else: | |
pop() | |
return False | |
if go(Point(p.x, p.y + 1)): # up | |
return True | |
elif go(Point(p.x + 1, p.y)): # right | |
return True | |
elif go(Point(p.x, p.y - 1)): # down | |
return True | |
elif go(Point(p.x - 1, p.y)): # left | |
return True | |
else: | |
pop() | |
return False | |
if not go(START): | |
print('No path found') | |
sys.exit(1) | |
else: | |
print_path = [''] * WIDTH * HEIGHT | |
max_length = len(str(WIDTH * HEIGHT)) | |
for i, p in enumerate(path): | |
print_path[p.x + p.y * WIDTH] = '{0:{1}d}'.format(i + 1, max_length) | |
for y in reversed(range(HEIGHT)): | |
for x in range(WIDTH): | |
print(print_path[x + y * WIDTH], end=', ') | |
print() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample output
3 x 3 maze from bottom left (0, 0) to bottom right (2, 0).
5 x 3 maze from bottom left (0, 0) to bottom right (4, 0).
3 x 5 maze from bottom left (0, 0) to bottom right (2, 0).
3 x 6 maze from bottom left (0, 0) to bottom right (2, 0).