2026-rff_mp/pomelovsd/ExitMaze/Strategies/AStar.py

41 lines
1.1 KiB
Python
Raw Normal View History

2026-05-23 10:37:43 +00:00
from Strategies.strat import PathFindingStrategy
2026-05-25 10:45:18 +00:00
from Strategies.path import restore
2026-05-22 20:58:06 +00:00
import heapq
class AStar(PathFindingStrategy):
def heuristic(self, a, b):
2026-05-25 10:45:18 +00:00
return abs(a.x - b.x) + abs(a.y - b.y)
2026-05-22 20:58:06 +00:00
def findPath(self, maze, start, exit):
2026-05-25 13:02:23 +00:00
if exit is None:
return [], 0
2026-05-25 10:45:18 +00:00
heap = []
counter = 0
heapq.heappush(heap, (0, counter, start))
counter += 1
2026-05-22 20:58:06 +00:00
parent = {}
g = {start: 0}
visited = set()
while heap:
2026-05-25 13:02:23 +00:00
_, _, current = heapq.heappop(heap)
2026-05-22 20:58:06 +00:00
if current == exit:
break
visited.add(current)
2026-05-25 10:45:18 +00:00
for n in maze.getNeighbors(current):
2026-05-22 20:58:06 +00:00
tentative = g[current] + 1
if n not in g or tentative < g[n]:
g[n] = tentative
priority = tentative + self.heuristic(n, exit)
2026-05-25 10:45:18 +00:00
heapq.heappush(heap, (priority, counter, n))
counter += 1
2026-05-22 20:58:06 +00:00
parent[n] = current
2026-05-25 10:45:18 +00:00
return restore(parent, start, exit), len(visited)