Реализован этап 3, добавлен A*, некоторые исправления

This commit is contained in:
oSTEVEo 2026-05-20 21:23:47 +03:00
parent d5f28df86a
commit 107d5cbd61
6 changed files with 43 additions and 6 deletions

View File

@ -140,7 +140,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.14.3"
"version": "3.14.5"
}
},
"nbformat": 4,

View File

@ -1,9 +1,45 @@
import heapq
from itertools import count
from task2.strategyObjects.pathFindingStrategy import PathFindingStrategy
from task2.strategyObjects.util import restorePath
from task2.mazeObjects.maze import Maze
from task2.mazeObjects.cell import Cell
class AStar(PathFindingStrategy):
"""Алгоритм с эвристикой (etc. манхэттенское расстояние) компромисс между скоростью и оптимальностью."""
def heuristic(self, first: Cell, second: Cell) -> int:
return abs(first.x - second.x) + abs(first.y - second.y)
def findPath(self, maze: Maze, start: Cell, exit: Cell):
...
tie_breaker = count()
start_heuristic = self.heuristic(start, exit)
heap: list[tuple[int, int, int, Cell]] = [
(start_heuristic, start_heuristic, next(tie_breaker), start)
]
g_score: dict[Cell, int] = {start: 0}
parents: dict[Cell, Cell | None] = {start: None}
visited: set[Cell] = set()
while heap:
_, _, _, current = heapq.heappop(heap)
if current in visited:
continue
visited.add(current)
if current == exit:
return restorePath(parents, exit)
for neighbor in maze.getNeighbors(current):
tentative_score = g_score[current]
if tentative_score < g_score.get(neighbor, 10**12):
g_score[neighbor] = tentative_score
parents[neighbor] = current
heuristic = self.heuristic(neighbor, exit)
priority = tentative_score + heuristic
heapq.heappush(
heap,
(priority, heuristic, next(tie_breaker), neighbor),
)
return []

View File

@ -31,4 +31,4 @@ class BFS(PathFindingStrategy):
visited[hood] = visited[current] + 1
parents[hood] = current
q.put(hood)
return restorePath(parents, start, exit)
return restorePath(parents, exit)

View File

@ -31,4 +31,4 @@ class DFS(PathFindingStrategy):
parents[hood] = current
stack.append(hood)
return restorePath(parents, start, exit)
return restorePath(parents, exit)

View File

@ -10,3 +10,4 @@ class PathFindingStrategy(ABC):
@abstractmethod
def findPath(self, maze: Maze, start: Cell, exit: Cell):
"""Возвращает список клеток пути от старта до выхода включительно. Пути нет - пустой список."""
raise NotImplementedError

View File

@ -1,7 +1,7 @@
from task2.mazeObjects.maze import Maze
from task2.mazeObjects.cell import Cell
def restorePath(parents: dict, start: Cell, exit: Cell) -> list[Cell]|None:
def restorePath(parents: dict, exit: Cell) -> list[Cell]|None:
path = []
current = exit
while current: