forked from UNN/2026-rff_mp
65 lines
2.0 KiB
Python
65 lines
2.0 KiB
Python
from heapq import *
|
|
|
|
|
|
from source.strategy import PathFindingStrategy, reconstruct_path
|
|
from source.classes import Maze, Cell
|
|
|
|
|
|
class AStar(PathFindingStrategy):
|
|
@property
|
|
def name(self) -> str:
|
|
return "A*"
|
|
|
|
def heuristic(self, a: Cell, b: Cell) -> int:
|
|
x1, y1 = a.getXY()
|
|
x2, y2 = b.getXY()
|
|
|
|
return abs(x1 - x2) + abs(y1 - y2)
|
|
|
|
def findPath(self, maze: Maze) -> tuple[list[Cell], int]:
|
|
start_cell = maze.start
|
|
exit_cell = maze.exit
|
|
|
|
queue = []
|
|
counter = 0 # счётчик для уникальности, чтобы не сравнивать клетки
|
|
|
|
start_h = self.heuristic(start_cell, exit_cell)
|
|
|
|
heappush(queue, (start_h, counter, start_cell))
|
|
counter += 1
|
|
|
|
cost_visited = {start_cell.getXY(): 0}
|
|
came_from = {start_cell.getXY(): None}
|
|
visited_count = 1
|
|
|
|
while queue:
|
|
current_cost, _, current_cell = heappop(queue)
|
|
current_g = cost_visited[current_cell.getXY()]
|
|
|
|
if current_cell.getXY() == exit_cell.getXY():
|
|
return reconstruct_path(
|
|
came_from=came_from,
|
|
start=start_cell,
|
|
end=current_cell
|
|
), visited_count
|
|
|
|
next_cells = maze.getNeighbors(current_cell)
|
|
|
|
for next_cell in next_cells:
|
|
neighbor_cost = next_cell.value
|
|
neighbor_cell_xy = next_cell.getXY()
|
|
|
|
new_cost = current_g + neighbor_cost
|
|
|
|
if neighbor_cell_xy not in cost_visited or new_cost < cost_visited[neighbor_cell_xy]:
|
|
priority = new_cost + self.heuristic(next_cell, exit_cell)
|
|
|
|
heappush(queue, (priority, counter, next_cell))
|
|
counter += 1
|
|
|
|
cost_visited[neighbor_cell_xy] = new_cost
|
|
came_from[neighbor_cell_xy] = current_cell
|
|
visited_count += 1
|
|
|
|
return [], visited_count
|