add MazeSolver
This commit is contained in:
parent
d04a7c0c47
commit
29495a0eda
0
pomelovsd/ExitMaze/MazeSolver/SearchStats.py
Normal file
0
pomelovsd/ExitMaze/MazeSolver/SearchStats.py
Normal file
20
pomelovsd/ExitMaze/MazeSolver/Solver.py
Normal file
20
pomelovsd/ExitMaze/MazeSolver/Solver.py
Normal 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
|
||||
|
|
@ -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)
|
||||
|
||||
Loading…
Reference in New Issue
Block a user