[2] implement maze solver with statistics collection
This commit is contained in:
parent
43ca559493
commit
3dc7e19f49
|
|
@ -2,6 +2,7 @@ import sys
|
||||||
import os
|
import os
|
||||||
from collections import deque
|
from collections import deque
|
||||||
import heapq
|
import heapq
|
||||||
|
import time
|
||||||
|
|
||||||
class GridPoint:
|
class GridPoint:
|
||||||
def __init__(self, x, y):
|
def __init__(self, x, y):
|
||||||
|
|
@ -174,6 +175,40 @@ class AStar(SearchAlgorithm):
|
||||||
self._visited = len(seen)
|
self._visited = len(seen)
|
||||||
return []
|
return []
|
||||||
|
|
||||||
|
class LabyrinthSolver:
|
||||||
|
def __init__(self, lab):
|
||||||
|
self.lab = lab
|
||||||
|
self.algorithm = None
|
||||||
|
|
||||||
|
def set_algorithm(self, algo):
|
||||||
|
self.algorithm = algo
|
||||||
|
|
||||||
|
def solve(self):
|
||||||
|
if not self.algorithm:
|
||||||
|
return None
|
||||||
|
t0 = time.perf_counter()
|
||||||
|
path = self.algorithm.find_way(self.lab, self.lab.start_point, self.lab.exit_point)
|
||||||
|
t1 = time.perf_counter()
|
||||||
|
ms = (t1 - t0) * 1000
|
||||||
|
return ms, self.algorithm.get_visited(), len(path)
|
||||||
|
|
||||||
|
def run_experiment(maze_file, algo, runs=5):
|
||||||
|
loader = TextMazeLoader()
|
||||||
|
lab = loader.load(maze_file)
|
||||||
|
total_ms = 0
|
||||||
|
total_visited = 0
|
||||||
|
total_len = 0
|
||||||
|
for _ in range(runs):
|
||||||
|
solver = LabyrinthSolver(lab)
|
||||||
|
solver.set_algorithm(algo)
|
||||||
|
stats = solver.solve()
|
||||||
|
if stats:
|
||||||
|
ms, vis, plen = stats
|
||||||
|
total_ms += ms
|
||||||
|
total_visited += vis
|
||||||
|
total_len += plen
|
||||||
|
return total_ms / runs, total_visited / runs, total_len / runs
|
||||||
|
|
||||||
class TextView:
|
class TextView:
|
||||||
def display(self, lab):
|
def display(self, lab):
|
||||||
os.system('cls' if os.name == 'nt' else 'clear')
|
os.system('cls' if os.name == 'nt' else 'clear')
|
||||||
|
|
@ -197,11 +232,12 @@ class TextView:
|
||||||
print(" S - start E - exit # - wall . - path")
|
print(" S - start E - exit # - wall . - path")
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
# quick demo
|
||||||
loader = TextMazeLoader()
|
loader = TextMazeLoader()
|
||||||
lab = loader.load("maze/maze1.txt")
|
lab = loader.load("maze/maze1.txt")
|
||||||
view = TextView()
|
view = TextView()
|
||||||
view.display(lab)
|
view.display(lab)
|
||||||
print("\nTesting BFS...")
|
print("\nRunning experiment on maze1.txt with BFS...")
|
||||||
bfs = BreadthFirst()
|
bfs = BreadthFirst()
|
||||||
path = bfs.find_way(lab, lab.start_point, lab.exit_point)
|
avg_t, avg_v, avg_l = run_experiment("maze/maze1.txt", bfs, runs=3)
|
||||||
print(f"BFS path length: {len(path)} visited: {bfs.get_visited()}")
|
print(f"BFS: time={avg_t:.3f}ms visited={avg_v:.0f} length={avg_l:.0f}")
|
||||||
Loading…
Reference in New Issue
Block a user