forked from UNN/2026-rff_mp
64 lines
2.0 KiB
Python
64 lines
2.0 KiB
Python
#!/usr/bin/env python
|
||
# coding: utf-8
|
||
|
||
# In[ ]:
|
||
|
||
|
||
import heapq
|
||
from typing import List, Dict, Optional, Tuple
|
||
from strategiesPathfinding_strategy import PathFindingStrategy
|
||
from modelsMaze import Maze
|
||
from modelsCell import Cell
|
||
|
||
class AStarStrategy(PathFindingStrategy):
|
||
"""Алгоритм A* с манхэттенской эвристикой."""
|
||
|
||
@property
|
||
def name(self) -> str:
|
||
return "A*"
|
||
|
||
def _heuristic(self, a: Cell, b: Cell) -> int:
|
||
"""Манхэттенское расстояние."""
|
||
return abs(a.x - b.x) + abs(a.y - b.y)
|
||
|
||
def find_path(self, maze: Maze, start: Cell, exit_cell: Cell) -> List[Cell]:
|
||
if start == exit_cell:
|
||
return [start]
|
||
|
||
# Приоритетная очередь: (f_score, counter, cell)
|
||
open_set = [(0, 0, start)]
|
||
counter = 1
|
||
|
||
came_from: Dict[Cell, Optional[Cell]] = {}
|
||
|
||
g_score: Dict[Cell, float] = {start: 0}
|
||
f_score: Dict[Cell, float] = {start: self._heuristic(start, exit_cell)}
|
||
|
||
visited_count = 0
|
||
|
||
while open_set:
|
||
current_f, _, current = heapq.heappop(open_set)
|
||
visited_count += 1
|
||
|
||
if current == exit_cell:
|
||
self._last_visited_count = visited_count
|
||
return self._reconstruct_path(came_from, start, current)
|
||
|
||
for neighbor in maze.get_neighbors(current):
|
||
tentative_g_score = g_score.get(current, float('inf')) + 1
|
||
|
||
if tentative_g_score < g_score.get(neighbor, float('inf')):
|
||
came_from[neighbor] = current
|
||
g_score[neighbor] = tentative_g_score
|
||
f_score[neighbor] = tentative_g_score + self._heuristic(neighbor, exit_cell)
|
||
heapq.heappush(open_set, (f_score[neighbor], counter, neighbor))
|
||
counter += 1
|
||
|
||
self._last_visited_count = visited_count
|
||
return []
|
||
|
||
@property
|
||
def last_visited_count(self) -> int:
|
||
return getattr(self, '_last_visited_count', 0)
|
||
|