add MazeSolver

This commit is contained in:
4eker 2026-05-22 23:58:06 +03:00
parent d04a7c0c47
commit 29495a0eda
3 changed files with 54 additions and 0 deletions

View File

@ -0,0 +1,20 @@
from SearchStats import SearchStats
import time
class MazeSolver:
def __init__(self, maze, strategy):
self.maze = maze
self.strategy = strategy
def setStrategy(self, strategy):
self.strategy = strategy
def solve(self):
start = time.perf_counter()
path, visited = self.strategy.findPath(self.maze, self.maze.start, self.maze.exit)
end = time.perf_counter()
return SearchStats((end-start)*1000, visited, len(path)), path

View File

@ -0,0 +1,34 @@
from strat import PathFindingStrategy
from path import restore
import heapq
class AStar(PathFindingStrategy):
def heuristic(self, a, b):
return abs(a.x - b.x)+ abs(a.y - b.y)
def findPath(self, maze, start, exit):
heap = [(0, start)]
parent = {}
g = {start: 0}
visited = set()
while heap:
_, current = heapq.heappop(heap)
if current == exit:
break
visited.add(current)
for n in maze.get_neigbors(current):
tentative = g[current] + 1
if n not in g or tentative < g[n]:
g[n] = tentative
priority = tentative + self.heuristic(n, exit)
heapq.heappush(heap, (priority, n))
parent[n] = current
return self.restore(parent, start, exit), len(visited)