[2] add Astar method

This commit is contained in:
IvanBud123 2026-05-15 08:52:56 +03:00
parent 617d205458
commit 57c743c253

View File

@ -1,5 +1,7 @@
import sys
from collections import deque
import heapq
from typing import List, Dict, Optional
class Cell:
@ -199,6 +201,45 @@ class DFSStrategy:
return path
class AStarStrategy:
def _heuristic(self, cell,exit_cell):
return abs(cell.x -exit_cell.x)+abs(cell.y-exit_cell.y)
def find_path(self,maze, start, exit_cell):
heap = []
counter = 0
start_f = 0 + self._heuristic(start,exit_cell)
heapq.heappush(heap, (start_f, counter, start))
counter +=1
came_from = {}
g_score = {start: 0}
f_score = {start: start_f}
while heap:
current_f, _, current = heapq.heappop(heap)
if current==exit_cell:
return self._reconstruct_path(came_from, start, exit_cell)
if current_f>f_score.get(current, float("inf")):
continue
for neighbor in maze.get_neighbors(current):
tentative_g = g_score[current] + 1
if tentative_g < g_score.get(neighbor, float('inf')):
came_from[neighbor] = current
g_score[neighbor] = tentative_g
new_f = tentative_g + self._heuristic(neighbor, exit_cell)
f_score[neighbor] = new_f
heapq.heappush(heap, (new_f, counter, neighbor))
counter += 1
return []
def _reconstruct_path(self, came_from, start, exit_cell):
path = []
current = exit_cell
while current is not None:
path.append(current)
current = came_from.get(current)
path.reverse()
return path
if __name__ == "__main__":
builder = TextFileMazeBuilder()
maze = builder.build_from_file("maze1.txt")
@ -211,3 +252,6 @@ if __name__ == "__main__":
dfs = DFSStrategy()
path = dfs.find_path(maze, maze.start, maze.exit)
print(f"DFS: путь найден, длинна = {len(path)}")
astar = AStarStrategy()
path = astar.find_path(maze, maze.start, maze.exit)
print(f"A*: путь найден, длина = {len(path)}")