From 3dc7e19f49775b277df489ce76bb6341d8df7ff8 Mon Sep 17 00:00:00 2001 From: BoriskovaDV Date: Sun, 24 May 2026 20:09:48 +0000 Subject: [PATCH] [2] implement maze solver with statistics collection --- BoriskovaDV/docs/data/2-nd-exercise/main.py | 42 +++++++++++++++++++-- 1 file changed, 39 insertions(+), 3 deletions(-) diff --git a/BoriskovaDV/docs/data/2-nd-exercise/main.py b/BoriskovaDV/docs/data/2-nd-exercise/main.py index ed50568..d081b64 100644 --- a/BoriskovaDV/docs/data/2-nd-exercise/main.py +++ b/BoriskovaDV/docs/data/2-nd-exercise/main.py @@ -2,6 +2,7 @@ import sys import os from collections import deque import heapq +import time class GridPoint: def __init__(self, x, y): @@ -174,6 +175,40 @@ class AStar(SearchAlgorithm): self._visited = len(seen) 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: def display(self, lab): os.system('cls' if os.name == 'nt' else 'clear') @@ -197,11 +232,12 @@ class TextView: print(" S - start E - exit # - wall . - path") if __name__ == "__main__": + # quick demo loader = TextMazeLoader() lab = loader.load("maze/maze1.txt") view = TextView() view.display(lab) - print("\nTesting BFS...") + print("\nRunning experiment on maze1.txt with BFS...") bfs = BreadthFirst() - path = bfs.find_way(lab, lab.start_point, lab.exit_point) - print(f"BFS path length: {len(path)} visited: {bfs.get_visited()}") \ No newline at end of file + avg_t, avg_v, avg_l = run_experiment("maze/maze1.txt", bfs, runs=3) + print(f"BFS: time={avg_t:.3f}ms visited={avg_v:.0f} length={avg_l:.0f}") \ No newline at end of file