-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsolveAStarSearch.py
61 lines (53 loc) · 2.67 KB
/
solveAStarSearch.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from solve import Solver
from priority_queue import PriorityQueue
from maze import Maze
class SolverAStarSearch(Solver):
def __init__(self, maze):
super().__init__(maze)
def solve(self):
pq = PriorityQueue(lambda x, y: x[3] >= y[3])
pq.push((0, 0, 0, 2 * (self.maze_dim - 1)))
visited = {}
parents = {}
distances = dict([((y, x), 1000 * self.maze_dim) for y in range(self.maze_dim) for x in range(self.maze_dim)])
while True:
while len(pq) > 0 and pq.peek()[:2] in visited:
pq.pop()
if len(pq) > 0:
y, x, dist, sc = pq.pop()
visited[(y, x)] = True
if y == self.maze_dim - 1 and x == self.maze_dim - 1:
break
else:
if x + 1 < self.maze_dim and (y, x + 1) not in visited and not self.maze_matrix[y][x + 1][1] and distances[(y, x + 1)] > dist + 1:
distances[(y, x + 1)] = dist + 1
parents[(y, x + 1)] = (y, x)
pq.push((y, x + 1, dist + 1, dist + 1 + 2 * (self.maze_dim - 1) - y - (x + 1)))
if y + 1 < self.maze_dim and (y + 1, x) not in visited and not self.maze_matrix[y + 1][x][0] and distances[(y + 1, x)] > dist + 1:
distances[(y + 1, x)] = dist + 1
parents[(y + 1, x)] = (y, x)
pq.push((y + 1, x, dist + 1, dist + 1 + 2 * (self.maze_dim - 1) - (y + 1) - x))
if x > 0 and (y, x - 1) not in visited and not self.maze_matrix[y][x][1] and distances[(y, x - 1)] > dist + 1:
distances[(y, x - 1)] = dist + 1
parents[(y, x - 1)] = (y, x)
pq.push((y, x - 1, dist + 1, dist + 1 + 2 * (self.maze_dim - 1) - y - (x - 1)))
if y > 0 and (y - 1, x) not in visited and not self.maze_matrix[y][x][0] and distances[(y - 1, x)] > dist + 1:
distances[(y - 1, x)] = dist + 1
parents[(y - 1, x)] = (y, x)
pq.push((y - 1, x, dist + 1, dist + 1 + 2 * (self.maze_dim - 1) - (y - 1) - x))
else:
break
y_start, x_start = self.maze_dim - 1, self.maze_dim - 1
while True:
self.solution.append((y_start, x_start))
if not (y_start == 0 and x_start == 0):
y_start, x_start = parents[(y_start, x_start)]
else:
break
if __name__ == '__main__':
maze = Maze(3)
maze.build()
solver = SolverAStarSearch(maze)
solver.solve()
print(maze)
print(solver.get_solution())