Created
September 17, 2018 05:30
-
-
Save Boot-Error/77787c576c9852897db3ef2d7c5c5aaf to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| #!/usr/bin/env python | |
| class Stack: | |
| def __init__(self): | |
| self.arr = [] | |
| def push(self, ele): | |
| self.arr.append(ele) | |
| def pop(self): | |
| return self.arr.pop() | |
| def isEmpty(self): | |
| return len(self.arr) == 0 | |
| def top(self): | |
| return self.arr[-1] | |
| maze = [ | |
| [0, 0, 0, 1, 1], | |
| [1, 0, 1, 1, 0], | |
| [1, 0, 0, 0, 0], | |
| [1, 1, 1, 0, 1], | |
| [1, 1, 1, 0, 1], | |
| ] | |
| dimen = (5, 5) | |
| move = { | |
| "up": lambda x, y: (x - 1, y), | |
| "down": lambda x, y: (x + 1, y), | |
| "left": lambda x, y: (x, y - 1), | |
| "right": lambda x, y: (x, y + 1), | |
| } | |
| def isBoundary(x, y): | |
| return any([x >= dimen[0], x < 0, y >= dimen[1], y < 0]) | |
| def isObstacle(x, y): | |
| return 1 if isBoundary(x, y) else maze[x][y] == 1 | |
| def solve(maze, start, end): | |
| s = Stack() | |
| s.push(start) | |
| visited = [] | |
| # start traversal | |
| curPos = start | |
| while curPos != end: | |
| curPos = s.top() | |
| for m in move.keys(): | |
| nextPos = move[m](*curPos) | |
| if isObstacle(*nextPos) or (nextPos in visited): | |
| continue | |
| else: | |
| print "Moving %s %s to %s " % (m, curPos, nextPos) | |
| visited.append(curPos) | |
| s.push(nextPos) | |
| curPos = nextPos | |
| break | |
| else: | |
| print "Backtrack: ", curPos | |
| curPos = s.pop() | |
| visited.append(curPos) | |
| showMarkedMaze(maze, s.arr) | |
| def showMarkedMaze(maze, blocks): | |
| for x, y in blocks: | |
| maze[x][y] = 8 | |
| for r in maze: | |
| print r | |
| if __name__ == "__main__": | |
| start = input("Enter start coordinates (x, y): ") | |
| end = input("Enter end coordinates (x, y): ") | |
| solve(maze, start, end) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment