34 lines
927 B
Python
34 lines
927 B
Python
from Strategies.strat import PathFindingStrategy
|
|
from path import restore
|
|
import heapq
|
|
|
|
class AStar(PathFindingStrategy):
|
|
|
|
def heuristic(self, a, b):
|
|
return abs(a.x - b.x)+ abs(a.y - b.y)
|
|
|
|
def findPath(self, maze, start, exit):
|
|
heap = [(0, start)]
|
|
parent = {}
|
|
g = {start: 0}
|
|
visited = set()
|
|
|
|
while heap:
|
|
_, current = heapq.heappop(heap)
|
|
|
|
if current == exit:
|
|
break
|
|
|
|
visited.add(current)
|
|
|
|
for n in maze.get_neigbors(current):
|
|
tentative = g[current] + 1
|
|
|
|
if n not in g or tentative < g[n]:
|
|
g[n] = tentative
|
|
priority = tentative + self.heuristic(n, exit)
|
|
heapq.heappush(heap, (priority, n))
|
|
parent[n] = current
|
|
|
|
return self.restore(parent, start, exit), len(visited)
|
|
|