Skip to content

Instantly share code, notes, and snippets.

@ronhuang
Created February 23, 2020 03:27
Show Gist options
  • Save ronhuang/c5991bc587fae23cb3bfbc5093280cd4 to your computer and use it in GitHub Desktop.
Save ronhuang/c5991bc587fae23cb3bfbc5093280cd4 to your computer and use it in GitHub Desktop.
Simple maze solver
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()
@ronhuang
Copy link
Author

Sample output

3 x 3 maze from bottom left (0, 0) to bottom right (2, 0).

> python .\solve.py 3 3 0 0 2 0
3, 4, 5,
2, 7, 6,
1, 8, 9,

5 x 3 maze from bottom left (0, 0) to bottom right (4, 0).

> python .\solve.py 5 3 0 0 4 0
 3,  4,  5,  6,  7,
 2, 11, 10,  9,  8,
 1, 12, 13, 14, 15,

3 x 5 maze from bottom left (0, 0) to bottom right (2, 0).

> python .\solve.py 3 5 0 0 2 0
 5,  6,  7, 
 4,  9,  8, 
 3, 10, 11,
 2, 13, 12,
 1, 14, 15,

3 x 6 maze from bottom left (0, 0) to bottom right (2, 0).

> python .\solve.py 3 6 0 0 2 0
No path found

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment