From 7e723606cbabf8224735965d4b3ae0dea431156a Mon Sep 17 00:00:00 2001 From: gutovvm Date: Mon, 25 May 2026 01:11:16 +0300 Subject: [PATCH] lab_2 Astar --- GutovVM/docs/data/lab_2_data/main.py | 61 ++++++++++++++++++++++++++-- 1 file changed, 58 insertions(+), 3 deletions(-) diff --git a/GutovVM/docs/data/lab_2_data/main.py b/GutovVM/docs/data/lab_2_data/main.py index 3da9999..3a0aa14 100644 --- a/GutovVM/docs/data/lab_2_data/main.py +++ b/GutovVM/docs/data/lab_2_data/main.py @@ -1,6 +1,7 @@ import numpy as np import abc from collections import deque +import heapq #Классы клетки и лабиринта @@ -163,7 +164,7 @@ class DFS(PathFindingStrategy): while stack: cell = stack.pop() - if cell == ex: + if cell.coords == ex.coords: #маршрут выстраивается в обратном порядке и разворачивается path = [] @@ -202,9 +203,9 @@ class BFS(PathFindingStrategy): while queue: cell = queue.popleft() - if cell == ex: + if cell.coords == ex.coords: + - #маршрут выстраивается в обратном порядке и разворачивается path = [] while cell.coords != st.coords: path.append(cell) @@ -226,3 +227,57 @@ path = BFS.findPath(maze,maze.st,maze.ex) print('путь поиском в ширину:') for cell in path: print(cell.coords) + +class Astar(PathFindingStrategy): + + def findPath(maze,st,ex): + + c = 0 + hp_queue = [(0,c,st)] + + g_score = {st.coords: 0} + + pathmap = {} + + hp_queue_coords = {st.coords} #нам важна скорость + + while hp_queue: + + cell = heapq.heappop(hp_queue)[2] + hp_queue_coords.remove(cell.coords) + + if cell.coords == ex.coords: + + path = [] + while cell.coords != st.coords: + path.append(cell) + cell = pathmap[cell.coords] + path.append(st) + path = path[::-1] + return path + + for n in maze.getNeighbors(cell): + new_g_score = g_score[cell.coords] + 1 + + if n is not None and new_g_score < g_score.get(n.coords, float('inf')): + pathmap[n.coords] = cell + g_score[n.coords] = new_g_score + + h_score = abs(n.coords[0]-ex.coords[0]) + abs(n.coords[1]-ex.coords[1]) + + #f = g + h + #h - манхэттенское расстояние + full_score = new_g_score + h_score + + if n.coords not in hp_queue_coords: + c += 1 + heapq.heappush(hp_queue, (full_score, c, n)) + hp_queue_coords.add(n.coords) + + return None + +path = Astar.findPath(maze,maze.st,maze.ex) + +print('путь с A*:') +for cell in path: + print(cell.coords) \ No newline at end of file