[2] labirint
This commit is contained in:
parent
b881e05410
commit
8c7cc741fe
153
shalovsa/lab2/docs/data/benchmark.py
Normal file
153
shalovsa/lab2/docs/data/benchmark.py
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
import time
|
||||
import csv
|
||||
import os
|
||||
import random
|
||||
|
||||
from maze_builder import TextFileMazeBuilder
|
||||
from maze_solver import MazeSolver
|
||||
from maze_strategies import BFSStrategy, DFSStrategy, AStarStrategy
|
||||
|
||||
REPEATS = 7
|
||||
OUTPUT_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
CSV_PATH = os.path.join(OUTPUT_DIR, 'results.csv')
|
||||
|
||||
STRATEGIES = {
|
||||
'BFS': BFSStrategy,
|
||||
'DFS': DFSStrategy,
|
||||
'A*': AStarStrategy,
|
||||
}
|
||||
|
||||
MAZES = [
|
||||
('small_10x10', 'maze_small.txt'),
|
||||
('medium_50x50', 'maze_medium.txt'),
|
||||
('large_100x100', 'maze_large.txt'),
|
||||
('open_50x50', 'maze_open.txt'),
|
||||
('no_exit_20x20', 'maze_no_exit.txt'),
|
||||
]
|
||||
|
||||
def _make_grid(width, height, density=0.0, has_exit=True, seed=42):
|
||||
|
||||
rng = random.Random(seed)
|
||||
grid = []
|
||||
for y in range(height):
|
||||
row = []
|
||||
for x in range(width):
|
||||
on_border = (x == 0 or x == width - 1 or y == 0 or y == height - 1)
|
||||
row.append('#' if on_border else ' ')
|
||||
grid.append(row)
|
||||
|
||||
for y in range(1, height - 1):
|
||||
for x in range(1, width - 1):
|
||||
if rng.random() < density:
|
||||
grid[y][x] = '#'
|
||||
|
||||
grid[1][1] = 'S'
|
||||
if has_exit:
|
||||
grid[height - 2][width - 2] = 'E'
|
||||
|
||||
return '\n'.join(''.join(row) for row in grid)
|
||||
|
||||
|
||||
def generate_maze_files():
|
||||
mazes_data = {
|
||||
'maze_small.txt': _make_grid(10, 10, density=0.15),
|
||||
'maze_medium.txt': _make_grid(50, 50, density=0.28),
|
||||
'maze_large.txt': _make_grid(100, 100, density=0.30),
|
||||
'maze_open.txt': _make_grid(50, 50, density=0.0),
|
||||
'maze_no_exit.txt': _make_grid(20, 20, density=0.20, has_exit=False),
|
||||
}
|
||||
no_exit = list(mazes_data['maze_no_exit.txt'].splitlines())
|
||||
no_exit[18] = no_exit[18][:18] + 'E' + no_exit[18][19:]
|
||||
no_exit[17] = no_exit[17][:18] + '#' + no_exit[17][19:]
|
||||
no_exit[18] = no_exit[18][:17] + '#' + no_exit[18][18:]
|
||||
mazes_data['maze_no_exit.txt'] = '\n'.join(no_exit)
|
||||
|
||||
maze_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
for fname, content in mazes_data.items():
|
||||
path = os.path.join(maze_dir, fname)
|
||||
with open(path, 'w', encoding='utf-8') as f:
|
||||
f.write(content)
|
||||
|
||||
print("✅ Файлы лабиринтов созданы")
|
||||
def avg(lst):
|
||||
return sum(lst) / len(lst) if lst else 0
|
||||
|
||||
|
||||
def run_benchmark():
|
||||
builder = TextFileMazeBuilder()
|
||||
maze_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
all_results = [
|
||||
['лабиринт', 'стратегия', 'время_мс', 'посещено_клеток', 'длина_пути']
|
||||
+ [f'замер_{i+1}' for i in range(REPEATS)]
|
||||
]
|
||||
|
||||
print(f"\nЗапуск бенчмарков (повторений: {REPEATS})\n")
|
||||
print(f" {'Лабиринт':<18} {'Алгоритм':<6} {'Время мс':>10} "
|
||||
f"{'Посещено':>10} {'Путь':>6}")
|
||||
print(' ' + '-' * 56)
|
||||
|
||||
for maze_label, maze_file in MAZES:
|
||||
maze_path = os.path.join(maze_dir, maze_file)
|
||||
try:
|
||||
maze = builder.build_from_file(maze_path)
|
||||
except Exception as e:
|
||||
print(f" ❌ {maze_file}: {e}")
|
||||
continue
|
||||
|
||||
solver = MazeSolver(maze)
|
||||
|
||||
for strat_name, StratClass in STRATEGIES.items():
|
||||
times_ms, visited_list, path_len = [], [], 0
|
||||
|
||||
for _ in range(REPEATS):
|
||||
strat = StratClass()
|
||||
solver.set_strategy(strat)
|
||||
stats = solver.solve()
|
||||
times_ms.append(stats.time_ms)
|
||||
visited_list.append(stats.visited_cells)
|
||||
path_len = stats.path_length
|
||||
|
||||
mean_t = avg(times_ms)
|
||||
mean_v = avg(visited_list)
|
||||
|
||||
print(f" {maze_label:<18} {strat_name:<6} "
|
||||
f"{mean_t:>10.3f} {mean_v:>10.0f} {path_len:>6}")
|
||||
|
||||
all_results.append([
|
||||
maze_label, strat_name,
|
||||
f"{mean_t:.4f}", f"{mean_v:.0f}", str(path_len)
|
||||
] + [f"{t:.4f}" for t in times_ms])
|
||||
|
||||
with open(CSV_PATH, 'w', newline='', encoding='utf-8') as f:
|
||||
csv.writer(f).writerows(all_results)
|
||||
|
||||
print(f"\n✅ Результаты сохранены: {CSV_PATH}")
|
||||
|
||||
def smoke_test():
|
||||
print("=== Smoke Test ===\n")
|
||||
|
||||
maze_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
test_path = os.path.join(maze_dir, '_test_maze.txt')
|
||||
|
||||
with open(test_path, 'w', encoding='utf-8') as f:
|
||||
f.write("#######\n#S #\n# #\n# E#\n#######")
|
||||
|
||||
builder = TextFileMazeBuilder()
|
||||
maze = builder.build_from_file(test_path)
|
||||
|
||||
for name, StratClass in STRATEGIES.items():
|
||||
strat = StratClass()
|
||||
path = strat.find_path(maze, maze.start, maze.exit)
|
||||
assert len(path) > 0, f"{name}: путь не найден!"
|
||||
assert path[0].is_start
|
||||
assert path[-1].is_exit
|
||||
print(f" ✅ {name}: путь длиной {len(path)} — OK")
|
||||
|
||||
os.remove(test_path)
|
||||
print("\nВсе тесты пройдены!\n")
|
||||
|
||||
if __name__ == '__main__':
|
||||
smoke_test()
|
||||
generate_maze_files()
|
||||
run_benchmark()
|
||||
BIN
shalovsa/lab2/docs/data/chart_время-мс.png
Normal file
BIN
shalovsa/lab2/docs/data/chart_время-мс.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 61 KiB |
BIN
shalovsa/lab2/docs/data/chart_длина-пути.png
Normal file
BIN
shalovsa/lab2/docs/data/chart_длина-пути.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 59 KiB |
BIN
shalovsa/lab2/docs/data/chart_посещено-клеток.png
Normal file
BIN
shalovsa/lab2/docs/data/chart_посещено-клеток.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 69 KiB |
44
shalovsa/lab2/docs/data/maze_builder.py
Normal file
44
shalovsa/lab2/docs/data/maze_builder.py
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
from abc import ABC, abstractmethod
|
||||
from maze_model import Cell, Maze
|
||||
|
||||
|
||||
class MazeBuilder(ABC):
|
||||
@abstractmethod
|
||||
def build_from_file(self, filename) -> Maze:
|
||||
pass
|
||||
|
||||
|
||||
class TextFileMazeBuilder(MazeBuilder):
|
||||
def build_from_file(self, filename) -> Maze:
|
||||
with open(filename, 'r', encoding='utf-8') as f:
|
||||
lines = f.read().splitlines()
|
||||
|
||||
width = max(len(line) for line in lines) if lines else 0
|
||||
height = len(lines)
|
||||
|
||||
cells = []
|
||||
start = None
|
||||
exit_cell = None
|
||||
|
||||
for y, line in enumerate(lines):
|
||||
row = []
|
||||
line = line.ljust(width)
|
||||
for x, char in enumerate(line):
|
||||
is_wall = (char == '#')
|
||||
is_start = (char == 'S')
|
||||
is_exit = (char == 'E')
|
||||
cell = Cell(x, y, is_wall=is_wall,
|
||||
is_start=is_start, is_exit=is_exit)
|
||||
if is_start:
|
||||
start = cell
|
||||
if is_exit:
|
||||
exit_cell = cell
|
||||
row.append(cell)
|
||||
cells.append(row)
|
||||
|
||||
if start is None:
|
||||
raise ValueError("В файле лабиринта не найден старт (S)")
|
||||
if exit_cell is None:
|
||||
raise ValueError("В файле лабиринта не найден выход (E)")
|
||||
|
||||
return Maze(width, height, cells, start, exit_cell)
|
||||
100
shalovsa/lab2/docs/data/maze_large.txt
Normal file
100
shalovsa/lab2/docs/data/maze_large.txt
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
####################################################################################################
|
||||
#S### # ## ## # # # ## ####### ## # # ## ## ## # # ### # #
|
||||
# # # # # # # # # # # # # # # # # ## ### # ## ## ## # ## ## #
|
||||
# # # # # # ## # # ## ## # # # # # ### # # # ### # # # # ## ##
|
||||
# ## ## ### # # # # # ### # # # ## # # # ## #
|
||||
# ## # ## #### # # # # # # ## ## #### ## # # # #
|
||||
### # # # # # # # # ### #### # # # ## # # # # # # # # #
|
||||
# # ## ## # ## ##### ## ###### # # ## # ## # # ## #### #
|
||||
# ## ## ## ## ## ## # # # # # # ## # # #
|
||||
## # # ## # # # # # # ## # # # # ## # # ###
|
||||
## # # # # # # # # ## ## # # # # ### ## # #
|
||||
## # # # # # ## # ## # ## # # #### ## # ## # # # ## ## # #
|
||||
# # # # # # ## # # ## # ## # # # # ### # # # # # # ### # #
|
||||
## # ## ## # # # # ### # ## ## # # ### ## # #
|
||||
## ## # # ## ### # # # # # # # # ## # # # # # #
|
||||
# ## # # ## # ### ## # # # ## # # # ## # # # #### # # # #
|
||||
# # # # # # # ## ## ## # # # # ### # # #
|
||||
# # # #### # # # # ## # ### # # #### # # # # # #
|
||||
# # # # # # ## # # # # # # # ## # ### # ##
|
||||
## # ### ## ## # # # # # # # # # # # # # # ### ## # #
|
||||
## ## ### # ## # # ### ## # # # # ## # # # # # # # #
|
||||
##### # # # #### # ## # # # # # # ### # ## # # # # #
|
||||
## # # ### # # # # ## # # # # # # #### # # # ### #
|
||||
# # ## ## # ### # # ## # ## ## ### # # # # # # # ###
|
||||
## ## # # # # # # # # # # ## ## # # ##
|
||||
# # # ### # # # # # ## # # # ### # # # # # ## ## ## # ## #
|
||||
# # # # # ##### # ## # # # # # # # # # ## ## # # # ##
|
||||
# # # # # # # ## # ## # # # # # # ## ### ## # # ##### #
|
||||
# # # # # ## # # ## # # ## # ## # # # # ## # # # ## #
|
||||
## ## # # # # # # ### # ## ### ## # ### # ## # # # ## # # ## # #
|
||||
# # # # #### # ## #### # # # # # # # # # # ### # ## # #
|
||||
# # ## # # # # # # # # # # ###### # ## # ## # # # #### #### # #
|
||||
# # ##### # # # ### # # # # # # # # # ## ### # #
|
||||
# # # # # # # ## # # ## # # ## # # # # # # # ## # # ###
|
||||
## # ## # # # # #### # # ## # ## ## # ## # # ## # #
|
||||
## # # # ## # # # # # # # # # # # # ###### # ## # # ## ### # #### # #
|
||||
## # # # # # # # # # # # ## # # # # # # ## # # # ## # ##
|
||||
## # # # ### # # # # # # # # # # # # # # ###
|
||||
# # ### # # # # # ## ## ## # # ## # ### ### # # #
|
||||
# # # # # ## # # ## ## # # # # # # ## ## ## #
|
||||
# ### # # ### # # # # ### # # # # # # # ## # ##
|
||||
# # ### ## ## ## ## # # ### # ## # # # # ## ## # # # # # #
|
||||
# ## # # # ## # # # # ## # ### #### # ## ###### ### #
|
||||
# # # # ### ### # # ## # # # ### ## # ## # # ## ##
|
||||
# # # ### #### # # # # ### # # # ## ### ## # ## #### # #
|
||||
# ### ## # # # # # # # # ### # # # # ## # ### ### ## #
|
||||
# # # # # # # # # # ## ### ## ### # ## # # # ## # #### # ## # #
|
||||
# # # # # # # # # # # ### # # # # # ## # # # # # # #
|
||||
# ## # # # # ## # # # # ## ## ## # # ## # ## # # ## # ## #
|
||||
# # # ## # # # # ### # # # # # # # ## # # # ## # ### ## # # #
|
||||
## # ## # ## ### ## # # # # ## # # # # # # #
|
||||
## ## # # ### # # # # # ## # # # # # ## # ## # # # #
|
||||
# # # ## # ### # ## # # ## # # # # # # # #
|
||||
# # # # # ## #### # # ### # ## # # ## # # ## #
|
||||
# # # # ## # ### # ## ## # # # # ### # # #
|
||||
# # # # # # # # # ## # ## ## ### ### # # ## # # # ## #
|
||||
# # # # ## # # ### ##### # # # # ## # # # # # ## # # #
|
||||
## # # # ## # # ## # ## ## # ## # ### # # # # #
|
||||
# ## ## # ### # ## ### # # ## # # # # # # # # # # # ###
|
||||
# ## # # # # # # # # # # # ## # # # # # # # # # # # ## #
|
||||
# # # # ## # # # # # ## # # ## # # ## # # # ### ### # # # ##
|
||||
# # # # ## # ## # # # # # # # ## # # ## # ### ##
|
||||
### # # ## ### # ## # # #### # # # # ##### # ## #### #
|
||||
# # # # # # # #### ## # ### ### # ## # ## # # ## # # # # # # ###
|
||||
# #### # ## # # # # # # ## # # # # # # # #
|
||||
# ## # # # # # # ## # ## ## # ### #### # # # # ## #
|
||||
# # ## # ## # # # # ## ## # ## # ## #
|
||||
# # # # # # # ## # # # # # # ### ## ### # ## # # ###
|
||||
### # # # ##### # ## ## # # # ## # ## ## # # # # # #
|
||||
# # # # # # ## ##### # ### # ## # # # ## # ### #### # #
|
||||
# # ### # ## # # ### ## ## # ## # ### # ## ### # ###
|
||||
# ## ## ## # # # # # # ### # ## # # ## # # # #
|
||||
## ## ## # ## # ## # # # ## # ## # ## # ## # # # #
|
||||
# # # # # # # # ## # # # ####### # ## ## ## ##
|
||||
# # # # # # # # # ## # # # # # ## # # ### # ##
|
||||
# # ## #### # # # # # ## ### # ### # ### # ### ## # # #
|
||||
## # # ## # # # # # # # # ## # ##### # ## ##### #### ###
|
||||
# # # # ## # ## # # ## # # ### ## ## # ######
|
||||
# # ## # # # # # # # # # ## ## # ## ## ## # ## # #
|
||||
### #### # # ## # # # # # ## # # ## # # # #### # # ## # #
|
||||
# ## ## # # ## # ## ## # # ## # # # # # #### # #
|
||||
# ## # # # ## ### ## #### # # # # # # ## ### # # # ##
|
||||
## # # # # # # # ## # ## ### # ## # ## # # # #
|
||||
# # # # # # # # # ### # # # ## # # ## ## # #### #
|
||||
# # ## # # # # # # # # # # ## ### # # # ##
|
||||
## ## # ## # # # ## # # # # # #### # # ## ### #
|
||||
## # ## ## # # # # ### # # ## # # # ## ## # # # # ## #
|
||||
# ## # ## # # #### # # # # # # ## # # # # # # ### #
|
||||
# ## # #### # # ## # # # # ### ## # ## ### # ## ## ##
|
||||
# # # # # # ## # # # ## # #### # ##### # # # # # # # #
|
||||
# # ## ## ### # ### ### # # #### # # # # ## # ## # # # # #### # #
|
||||
# # # # ## # # ## # # ## # # ## # ## # # # ## ## #
|
||||
# # ## # # # ## ## # ### ## # ## # # # # # # # ## # # #
|
||||
# # ## # ## ## ## # # ## # # # # # ## # # # # ### # #
|
||||
# # # ## # # # # # # # # # # # # ## # # # ## # # #
|
||||
## # ## # # # # ## # # ## # # # # # # ## # # # # # # # #
|
||||
# # ## # ## # ### # # ### # ## # # # ## # ### # ## # #
|
||||
# # # ## # # ## # # # ## # # #### ## # # # ### # ##
|
||||
# #### ## ### ### # # ### # # ## # # # ### # ####### # ## # #E#
|
||||
####################################################################################################
|
||||
50
shalovsa/lab2/docs/data/maze_medium.txt
Normal file
50
shalovsa/lab2/docs/data/maze_medium.txt
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
##################################################
|
||||
#S### # ## ## # # # ## ## #####
|
||||
# ## # # ## ## ## # # ### # #
|
||||
# # # # # # # # # # # # # # #
|
||||
# # # ## ### # ## ## ## # ## ##
|
||||
## # # # # # # # # ## ## # #
|
||||
# # # # ### # # ### # # # ##
|
||||
# ## # ## ## ### # # # # #
|
||||
## ### # # # ## # # # #
|
||||
# # # # ## #### # # # # # #
|
||||
## ## ## ## # ## # # #
|
||||
# # ## # # # # # # # # ### ##
|
||||
#### # # # ## # # # # # #
|
||||
# # # # # ## ## # ## ######
|
||||
# ## ##### # # ## # ## # # #
|
||||
# ## #### # ## # ## ##
|
||||
## ## # # # # #
|
||||
## ## # # # # # # # ##
|
||||
# # # # ## # #
|
||||
## # ## # # ### # # # # # # #
|
||||
# # ## # # # # #
|
||||
# ### ## # # # # # # # ###
|
||||
# # ## # ## # # #### ## # ## # # ##
|
||||
# ## ## # # # # # # ## # #
|
||||
# # ## # ## # # # # ### #
|
||||
# # # # # # ### # # # ## ## ##
|
||||
# # # # ### # ## ## # # #
|
||||
# ### ## # ## # #
|
||||
# ## ### # # # # # # #
|
||||
# ## # # # # ## # # # # ##
|
||||
### # # # # ## # # # ## # #
|
||||
## # ### # # # # # #
|
||||
# # # # # ## ## ## # #
|
||||
# # # ### # # # # ###
|
||||
### # # # # ## ## # #
|
||||
# # ### # # # # # # ##
|
||||
# # # # ## # # #
|
||||
# # # # ## # ### # ## # # #
|
||||
### # # # # # # # # # #
|
||||
# # # # # ### ## # # ## ### #
|
||||
# # ## # ### ## # # # # ## # #
|
||||
# # # # # # # ### #
|
||||
## # # #### # ## # # # # #
|
||||
# # ### # ## # # # # # #
|
||||
# # # ### # # # # ## # #
|
||||
## # # # # #### # # # ### #
|
||||
## ## ## # ### # # ## #
|
||||
# # ## ## ### # # # # # # ### #
|
||||
# ## # # # # # E#
|
||||
##################################################
|
||||
62
shalovsa/lab2/docs/data/maze_model.py
Normal file
62
shalovsa/lab2/docs/data/maze_model.py
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
class Cell:
|
||||
def __init__(self, x, y, is_wall=False, is_start=False, is_exit=False):
|
||||
self.x = x
|
||||
self.y = y
|
||||
self.is_wall = is_wall
|
||||
self.is_start = is_start
|
||||
self.is_exit = is_exit
|
||||
|
||||
def is_passable(self):
|
||||
return not self.is_wall
|
||||
|
||||
def __repr__(self):
|
||||
if self.is_wall:
|
||||
return '#'
|
||||
if self.is_start:
|
||||
return 'S'
|
||||
if self.is_exit:
|
||||
return 'E'
|
||||
return ' '
|
||||
|
||||
|
||||
class Maze:
|
||||
def __init__(self, width, height, cells, start, exit_cell):
|
||||
self.width = width
|
||||
self.height = height
|
||||
self._cells = cells
|
||||
self.start = start
|
||||
self.exit = exit_cell
|
||||
|
||||
def get_cell(self, x, y):
|
||||
if 0 <= x < self.width and 0 <= y < self.height:
|
||||
return self._cells[y][x]
|
||||
return None
|
||||
|
||||
def get_neighbors(self, cell):
|
||||
directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]
|
||||
neighbors = []
|
||||
for dx, dy in directions:
|
||||
neighbor = self.get_cell(cell.x + dx, cell.y + dy)
|
||||
if neighbor is not None and neighbor.is_passable():
|
||||
neighbors.append(neighbor)
|
||||
return neighbors
|
||||
|
||||
def render(self, path=None, player_pos=None):
|
||||
path_set = set((c.x, c.y) for c in path) if path else set()
|
||||
|
||||
for row in self._cells:
|
||||
line = ''
|
||||
for cell in row:
|
||||
if player_pos and cell.x == player_pos.x and cell.y == player_pos.y:
|
||||
line += 'P'
|
||||
elif cell.is_wall:
|
||||
line += '#'
|
||||
elif cell.is_start:
|
||||
line += 'S'
|
||||
elif cell.is_exit:
|
||||
line += 'E'
|
||||
elif (cell.x, cell.y) in path_set:
|
||||
line += '.'
|
||||
else:
|
||||
line += ' '
|
||||
print(line)
|
||||
20
shalovsa/lab2/docs/data/maze_no_exit.txt
Normal file
20
shalovsa/lab2/docs/data/maze_no_exit.txt
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
####################
|
||||
#S# # # ## #
|
||||
# # # ## #
|
||||
# # # # #
|
||||
# # # # #
|
||||
# ###
|
||||
## # # # #
|
||||
# # # # #
|
||||
## # # # # #
|
||||
# # # #
|
||||
# # # ## #
|
||||
# # # ##
|
||||
# # # #
|
||||
# # # # ## #
|
||||
# # #
|
||||
## # # ##
|
||||
# ### ##
|
||||
# # ## ###
|
||||
# # # #E#
|
||||
####################
|
||||
50
shalovsa/lab2/docs/data/maze_open.txt
Normal file
50
shalovsa/lab2/docs/data/maze_open.txt
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
##################################################
|
||||
#S #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# #
|
||||
# E#
|
||||
##################################################
|
||||
10
shalovsa/lab2/docs/data/maze_small.txt
Normal file
10
shalovsa/lab2/docs/data/maze_small.txt
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
##########
|
||||
#S# ##
|
||||
# # # #
|
||||
# # #
|
||||
# ## #
|
||||
# #
|
||||
# # # # #
|
||||
# #
|
||||
# E#
|
||||
##########
|
||||
121
shalovsa/lab2/docs/data/maze_solver.py
Normal file
121
shalovsa/lab2/docs/data/maze_solver.py
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
import time
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
class SearchStats:
|
||||
def __init__(self, time_ms, visited_cells, path_length, path):
|
||||
self.time_ms = time_ms
|
||||
self.visited_cells = visited_cells
|
||||
self.path_length = path_length
|
||||
self.path = path
|
||||
|
||||
def __repr__(self):
|
||||
return (f"SearchStats(time={self.time_ms:.3f}ms, "
|
||||
f"visited={self.visited_cells}, "
|
||||
f"path_len={self.path_length})")
|
||||
|
||||
class Observer(ABC):
|
||||
|
||||
@abstractmethod
|
||||
def update(self, event, data=None):
|
||||
pass
|
||||
|
||||
|
||||
class ConsoleView(Observer):
|
||||
|
||||
def update(self, event, data=None):
|
||||
if event == 'maze_loaded':
|
||||
print(f"\n[ConsoleView] Лабиринт загружен: "
|
||||
f"{data['width']}×{data['height']}")
|
||||
|
||||
elif event == 'path_found':
|
||||
stats = data['stats']
|
||||
strategy_name = data['strategy']
|
||||
if stats.path_length > 0:
|
||||
print(f"\n[ConsoleView] [{strategy_name}] Путь найден! "
|
||||
f"Длина: {stats.path_length}, "
|
||||
f"Посещено клеток: {stats.visited_cells}, "
|
||||
f"Время: {stats.time_ms:.3f} мс")
|
||||
else:
|
||||
print(f"\n[ConsoleView] [{strategy_name}] Путь не найден. "
|
||||
f"Посещено клеток: {stats.visited_cells}")
|
||||
|
||||
elif event == 'move':
|
||||
print(f"[ConsoleView] Игрок переместился в "
|
||||
f"({data['x']}, {data['y']})")
|
||||
|
||||
class MazeSolver:
|
||||
def __init__(self, maze, strategy=None):
|
||||
self.maze = maze
|
||||
self.strategy = strategy
|
||||
self._observers = []
|
||||
|
||||
def set_strategy(self, strategy):
|
||||
self.strategy = strategy
|
||||
|
||||
def add_observer(self, observer):
|
||||
self._observers.append(observer)
|
||||
|
||||
def _notify(self, event, data=None):
|
||||
for obs in self._observers:
|
||||
obs.update(event, data)
|
||||
|
||||
def solve(self):
|
||||
if self.strategy is None:
|
||||
raise RuntimeError("Стратегия не задана. Используйте set_strategy().")
|
||||
|
||||
start = time.perf_counter()
|
||||
path = self.strategy.find_path(self.maze, self.maze.start, self.maze.exit)
|
||||
end = time.perf_counter()
|
||||
|
||||
stats = SearchStats(
|
||||
time_ms=(end - start) * 1000,
|
||||
visited_cells=getattr(self.strategy, 'visited_count', 0),
|
||||
path_length=len(path),
|
||||
path=path
|
||||
)
|
||||
|
||||
self._notify('path_found', {
|
||||
'stats': stats,
|
||||
'strategy': type(self.strategy).__name__
|
||||
})
|
||||
|
||||
return stats
|
||||
|
||||
class Command(ABC):
|
||||
@abstractmethod
|
||||
def execute(self):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def undo(self):
|
||||
pass
|
||||
|
||||
|
||||
class Player:
|
||||
def __init__(self, start_cell):
|
||||
self.current_cell = start_cell
|
||||
|
||||
def move_to(self, cell):
|
||||
self.current_cell = cell
|
||||
|
||||
|
||||
class MoveCommand(Command):
|
||||
def __init__(self, player, target_cell, observers=None):
|
||||
self.player = player
|
||||
self.target_cell = target_cell
|
||||
self.previous_cell = None
|
||||
self._observers = observers or []
|
||||
|
||||
def execute(self):
|
||||
self.previous_cell = self.player.current_cell
|
||||
self.player.move_to(self.target_cell)
|
||||
for obs in self._observers:
|
||||
obs.update('move', {'x': self.target_cell.x,
|
||||
'y': self.target_cell.y})
|
||||
|
||||
def undo(self):
|
||||
if self.previous_cell is not None:
|
||||
self.player.move_to(self.previous_cell)
|
||||
for obs in self._observers:
|
||||
obs.update('move', {'x': self.previous_cell.x,
|
||||
'y': self.previous_cell.y})
|
||||
100
shalovsa/lab2/docs/data/maze_strategies.py
Normal file
100
shalovsa/lab2/docs/data/maze_strategies.py
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
from abc import ABC, abstractmethod
|
||||
from collections import deque
|
||||
import heapq
|
||||
|
||||
|
||||
class PathFindingStrategy(ABC):
|
||||
@abstractmethod
|
||||
def find_path(self, maze, start, exit_cell):
|
||||
pass
|
||||
|
||||
|
||||
def _reconstruct_path(came_from, start, exit_cell):
|
||||
path = []
|
||||
current = exit_cell
|
||||
while current is not None:
|
||||
path.append(current)
|
||||
current = came_from.get((current.x, current.y))
|
||||
path.reverse()
|
||||
if path and path[0].x == start.x and path[0].y == start.y:
|
||||
return path
|
||||
return []
|
||||
|
||||
class BFSStrategy(PathFindingStrategy):
|
||||
def find_path(self, maze, start, exit_cell):
|
||||
queue = deque([start])
|
||||
came_from = {(start.x, start.y): None}
|
||||
self.visited_count = 0
|
||||
|
||||
while queue:
|
||||
current = queue.popleft()
|
||||
self.visited_count += 1
|
||||
|
||||
if current.x == exit_cell.x and current.y == exit_cell.y:
|
||||
return _reconstruct_path(came_from, start, exit_cell)
|
||||
|
||||
for neighbor in maze.get_neighbors(current):
|
||||
key = (neighbor.x, neighbor.y)
|
||||
if key not in came_from:
|
||||
came_from[key] = current
|
||||
queue.append(neighbor)
|
||||
|
||||
self.visited_count = len(came_from)
|
||||
return [] # путь не найден
|
||||
|
||||
class DFSStrategy(PathFindingStrategy):
|
||||
|
||||
def find_path(self, maze, start, exit_cell):
|
||||
stack = [start]
|
||||
came_from = {(start.x, start.y): None}
|
||||
self.visited_count = 0
|
||||
|
||||
while stack:
|
||||
current = stack.pop()
|
||||
self.visited_count += 1
|
||||
|
||||
if current.x == exit_cell.x and current.y == exit_cell.y:
|
||||
return _reconstruct_path(came_from, start, exit_cell)
|
||||
|
||||
for neighbor in maze.get_neighbors(current):
|
||||
key = (neighbor.x, neighbor.y)
|
||||
if key not in came_from:
|
||||
came_from[key] = current
|
||||
stack.append(neighbor)
|
||||
|
||||
self.visited_count = len(came_from)
|
||||
return []
|
||||
|
||||
class AStarStrategy(PathFindingStrategy):
|
||||
|
||||
def _heuristic(self, cell, goal):
|
||||
return abs(cell.x - goal.x) + abs(cell.y - goal.y)
|
||||
|
||||
def find_path(self, maze, start, exit_cell):
|
||||
# (f_score, счётчик для разрыва связей, клетка)
|
||||
counter = 0
|
||||
open_set = [(0, counter, start)]
|
||||
came_from = {(start.x, start.y): None}
|
||||
g_score = {(start.x, start.y): 0}
|
||||
self.visited_count = 0
|
||||
|
||||
while open_set:
|
||||
_, _, current = heapq.heappop(open_set)
|
||||
self.visited_count += 1
|
||||
|
||||
if current.x == exit_cell.x and current.y == exit_cell.y:
|
||||
return _reconstruct_path(came_from, start, exit_cell)
|
||||
|
||||
for neighbor in maze.get_neighbors(current):
|
||||
key = (neighbor.x, neighbor.y)
|
||||
tentative_g = g_score[(current.x, current.y)] + 1
|
||||
|
||||
if key not in g_score or tentative_g < g_score[key]:
|
||||
g_score[key] = tentative_g
|
||||
f = tentative_g + self._heuristic(neighbor, exit_cell)
|
||||
counter += 1
|
||||
heapq.heappush(open_set, (f, counter, neighbor))
|
||||
came_from[key] = current
|
||||
|
||||
self.visited_count = len(came_from)
|
||||
return []
|
||||
103
shalovsa/lab2/docs/data/plot_results.py
Normal file
103
shalovsa/lab2/docs/data/plot_results.py
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
import csv
|
||||
import os
|
||||
|
||||
try:
|
||||
import matplotlib.pyplot as plt
|
||||
import matplotlib.patches as mpatches
|
||||
HAS_MPL = True
|
||||
except ImportError:
|
||||
HAS_MPL = False
|
||||
print("⚠️ matplotlib не установлен: pip install matplotlib\n")
|
||||
|
||||
CSV_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'results.csv')
|
||||
OUT_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
COLORS = {'BFS': '#4E9AF1', 'DFS': '#F4845F', 'A*': '#6BCB77'}
|
||||
STRATEGIES = ['BFS', 'DFS', 'A*']
|
||||
METRICS = [
|
||||
('время_мс', 'Среднее время (мс)'),
|
||||
('посещено_клеток', 'Посещено клеток'),
|
||||
('длина_пути', 'Длина пути (шагов)'),
|
||||
]
|
||||
|
||||
|
||||
def load_csv(path):
|
||||
data = {}
|
||||
with open(path, newline='', encoding='utf-8') as f:
|
||||
reader = csv.DictReader(f)
|
||||
for row in reader:
|
||||
key = (row['лабиринт'], row['стратегия'])
|
||||
data[key] = {
|
||||
'время_мс': float(row['время_мс']),
|
||||
'посещено_клеток': float(row['посещено_клеток']),
|
||||
'длина_пути': float(row['длина_пути']),
|
||||
}
|
||||
return data
|
||||
|
||||
|
||||
def get_mazes(data):
|
||||
seen = []
|
||||
for (maze, _) in data:
|
||||
if maze not in seen:
|
||||
seen.append(maze)
|
||||
return seen
|
||||
|
||||
|
||||
def plot_by_metric(data):
|
||||
mazes = get_mazes(data)
|
||||
x = range(len(mazes))
|
||||
w = 0.25
|
||||
|
||||
for metric_key, metric_label in METRICS:
|
||||
fig, ax = plt.subplots(figsize=(12, 5))
|
||||
fig.suptitle(f'{metric_label} по лабиринтам', fontweight='bold')
|
||||
|
||||
for i, strat in enumerate(STRATEGIES):
|
||||
vals = [data.get((m, strat), {}).get(metric_key, 0) for m in mazes]
|
||||
offset = [xi + (i - 1) * w for xi in x]
|
||||
bars = ax.bar(offset, vals, width=w,
|
||||
label=strat, color=COLORS[strat], edgecolor='white')
|
||||
for bar, val in zip(bars, vals):
|
||||
if val > 0:
|
||||
ax.text(bar.get_x() + bar.get_width() / 2,
|
||||
bar.get_height() + max(vals) * 0.01,
|
||||
f'{val:.1f}', ha='center', va='bottom', fontsize=7)
|
||||
|
||||
ax.set_xticks(list(x))
|
||||
ax.set_xticklabels(mazes, rotation=15, ha='right', fontsize=9)
|
||||
ax.set_ylabel(metric_label)
|
||||
ax.legend()
|
||||
ax.grid(axis='y', alpha=0.3)
|
||||
|
||||
safe = metric_key.replace('_', '-')
|
||||
out = os.path.join(OUT_DIR, f'chart_{safe}.png')
|
||||
plt.tight_layout()
|
||||
plt.savefig(out, dpi=150, bbox_inches='tight')
|
||||
print(f"✅ График сохранён: {out}")
|
||||
plt.show()
|
||||
|
||||
|
||||
def print_table(data):
|
||||
print(f"\n{'Лабиринт':<20} {'Алгоритм':<6} "
|
||||
f"{'Время мс':>10} {'Посещено':>10} {'Путь':>6}")
|
||||
print('-' * 56)
|
||||
for (maze, strat), vals in sorted(data.items()):
|
||||
print(f"{maze:<20} {strat:<6} "
|
||||
f"{vals['время_мс']:>10.3f} "
|
||||
f"{vals['посещено_клеток']:>10.0f} "
|
||||
f"{vals['длина_пути']:>6.0f}")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if not os.path.exists(CSV_PATH):
|
||||
print(f"❌ Файл не найден: {CSV_PATH}")
|
||||
print(" Сначала запустите: python benchmark.py")
|
||||
exit(1)
|
||||
|
||||
data = load_csv(CSV_PATH)
|
||||
print_table(data)
|
||||
|
||||
if HAS_MPL:
|
||||
plot_by_metric(data)
|
||||
else:
|
||||
print("\n💡 Установите matplotlib: pip install matplotlib")
|
||||
16
shalovsa/lab2/docs/data/results.csv
Normal file
16
shalovsa/lab2/docs/data/results.csv
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
лабиринт,стратегия,время_мс,посещено_клеток,длина_пути,замер_1,замер_2,замер_3,замер_4,замер_5,замер_6,замер_7
|
||||
small_10x10,BFS,0.0787,54,15,0.0931,0.0795,0.0790,0.0849,0.0721,0.0722,0.0704
|
||||
small_10x10,DFS,0.0509,33,33,0.0514,0.0463,0.0440,0.0446,0.0447,0.0567,0.0684
|
||||
small_10x10,A*,0.0709,36,15,0.0792,0.0729,0.0702,0.0731,0.0707,0.0659,0.0642
|
||||
medium_50x50,BFS,2.0810,1639,95,2.1951,2.0908,2.0562,2.0949,2.0368,2.0297,2.0632
|
||||
medium_50x50,DFS,1.3492,1063,185,1.3530,1.3543,1.3406,1.3454,1.3916,1.3317,1.3278
|
||||
medium_50x50,A*,1.1982,588,95,1.2252,1.1942,1.1866,1.1937,1.1808,1.2248,1.1821
|
||||
large_100x100,BFS,8.5772,6564,0,8.9067,8.5676,8.4910,8.5273,8.5058,8.5506,8.4913
|
||||
large_100x100,DFS,8.5785,6564,0,8.5521,8.4862,8.5502,8.4667,8.4953,8.4717,9.0270
|
||||
large_100x100,A*,16.7095,6564,0,14.4629,15.5478,19.9577,17.3113,17.0947,15.8721,16.7202
|
||||
open_50x50,BFS,3.4145,2304,95,3.5435,3.4067,3.3571,3.5743,3.5422,3.2572,3.2204
|
||||
open_50x50,DFS,1.8459,1223,1129,1.9151,1.8672,1.8296,1.8533,1.8246,1.8179,1.8139
|
||||
open_50x50,A*,4.9859,2304,95,5.0583,5.0246,4.9598,4.9387,4.9481,5.0107,4.9611
|
||||
no_exit_20x20,BFS,0.3292,260,0,0.3427,0.3298,0.3262,0.3330,0.3251,0.3231,0.3246
|
||||
no_exit_20x20,DFS,0.3275,260,0,0.3355,0.3280,0.3289,0.3289,0.3178,0.3279,0.3253
|
||||
no_exit_20x20,A*,0.5116,260,0,0.5235,0.5392,0.5083,0.4989,0.5043,0.4978,0.5095
|
||||
|
275
shalovsa/lab2/docs/report_maze_final.md
Normal file
275
shalovsa/lab2/docs/report_maze_final.md
Normal file
|
|
@ -0,0 +1,275 @@
|
|||
# Отчёт: Поиск выхода из лабиринта (ООП + паттерны проектирования)
|
||||
|
||||
## Цель работы
|
||||
|
||||
Разработать гибкую расширяемую программу для загрузки лабиринта из файла, поиска пути от старта до выхода с возможностью выбора алгоритма и экспериментального сравнения алгоритмов. Применить минимум 3 паттерна проектирования из списка GoF, обосновать их выбор и продемонстрировать преимущества такой архитектуры.
|
||||
|
||||
---
|
||||
|
||||
## Описание задачи и выбранных паттернов
|
||||
|
||||
Программа решает задачу поиска пути в лабиринте, загружаемом из текстового файла. Лабиринт представляет собой сетку клеток, где `#` — стена, пробел — проход, `S` — старт, `E` — выход. Алгоритм поиска выбирается динамически, результаты выводятся через систему событий.
|
||||
|
||||
Применены **4 паттерна GoF**: Builder, Strategy, Observer, Command.
|
||||
|
||||
### 1. Builder (Строитель) — `maze_builder.py`
|
||||
|
||||
**Проблема:** построение объекта `Maze` из файла — многошаговый процесс: открыть файл, разобрать символы, создать объекты `Cell`, установить координаты, найти старт и выход, собрать двумерный массив. Смешивать это с основной логикой нельзя.
|
||||
|
||||
**Решение:** интерфейс `MazeBuilder` с единственным методом `build_from_file(filename)` и реализация `TextFileMazeBuilder`, инкапсулирующая весь парсинг.
|
||||
|
||||
**Преимущество без паттерна было бы сложно:** при добавлении поддержки JSON-лабиринтов пришлось бы встраивать ветвление прямо в клиентский код. С Builder — просто создаём `JsonFileMazeBuilder` и подставляем без изменений в остальном коде.
|
||||
|
||||
### 2. Strategy (Стратегия) — `maze_strategies.py`
|
||||
|
||||
**Проблема:** алгоритмы BFS, DFS и A* принципиально различаются по реализации, но выполняют одну задачу — найти путь. Жёсткое встраивание алгоритма в `MazeSolver` делало бы переключение невозможным без правки класса.
|
||||
|
||||
**Решение:** интерфейс `PathFindingStrategy` с методом `find_path(maze, start, exit)`. Каждый алгоритм реализует интерфейс независимо. `MazeSolver.set_strategy()` меняет алгоритм в одну строку во время выполнения.
|
||||
|
||||
**Преимущество без паттерна было бы сложно:** добавление Dijkstra или любого нового алгоритма потребовало бы правки `MazeSolver`. С Strategy — новый алгоритм добавляется одним классом, остальной код не меняется.
|
||||
|
||||
### 3. Observer (Наблюдатель) — `maze_solver.py`
|
||||
|
||||
**Проблема:** `MazeSolver` должен уведомлять интерфейс о событиях (путь найден, лабиринт загружен), но не должен знать, кто именно получает эти уведомления.
|
||||
|
||||
**Решение:** интерфейс `Observer` с методом `update(event, data)`. `ConsoleView` реализует интерфейс и подписывается на `MazeSolver`. При наступлении события вызывается `_notify()`, который обходит список подписчиков.
|
||||
|
||||
**Преимущество без паттерна было бы сложно:** прямой вызов `ConsoleView` из `MazeSolver` создаёт жёсткую зависимость. С Observer — `ConsoleView` можно отключить, заменить на GUI или добавить файловый логгер без единой правки в `MazeSolver`.
|
||||
|
||||
### 4. Command (Команда) — `maze_solver.py`
|
||||
|
||||
**Проблема:** для пошагового режима нужно перемещать игрока с возможностью отмены хода.
|
||||
|
||||
**Решение:** интерфейс `Command` с методами `execute()` и `undo()`. `MoveCommand` хранит целевую клетку и предыдущую позицию игрока. История команд — обычный стек.
|
||||
|
||||
**Преимущество без паттерна было бы сложно:** прямое изменение позиции игрока не сохраняет историю. С Command — `undo()` возвращает игрока на шаг назад, а добавление новых типов действий (атака, открыть дверь) не требует изменения `Player`.
|
||||
|
||||
---
|
||||
|
||||
## Диаграмма классов (Mermaid)
|
||||
|
||||
```mermaid
|
||||
classDiagram
|
||||
class MazeBuilder {
|
||||
<<interface>>
|
||||
+build_from_file(filename) Maze
|
||||
}
|
||||
class TextFileMazeBuilder {
|
||||
+build_from_file(filename) Maze
|
||||
}
|
||||
class Maze {
|
||||
-int width, height
|
||||
-Cell[][] cells
|
||||
-Cell start
|
||||
-Cell exit
|
||||
+get_cell(x, y) Cell
|
||||
+get_neighbors(cell) list
|
||||
+render(path, player_pos)
|
||||
}
|
||||
class Cell {
|
||||
-int x, y
|
||||
-bool is_wall
|
||||
-bool is_start
|
||||
-bool is_exit
|
||||
+is_passable() bool
|
||||
}
|
||||
class PathFindingStrategy {
|
||||
<<interface>>
|
||||
+find_path(maze, start, exit) list
|
||||
}
|
||||
class BFSStrategy { +find_path() }
|
||||
class DFSStrategy { +find_path() }
|
||||
class AStarStrategy { +find_path() }
|
||||
class MazeSolver {
|
||||
-Maze maze
|
||||
-PathFindingStrategy strategy
|
||||
-list observers
|
||||
+set_strategy(strategy)
|
||||
+add_observer(observer)
|
||||
+solve() SearchStats
|
||||
}
|
||||
class SearchStats {
|
||||
+float time_ms
|
||||
+int visited_cells
|
||||
+int path_length
|
||||
+list path
|
||||
}
|
||||
class Observer {
|
||||
<<interface>>
|
||||
+update(event, data)
|
||||
}
|
||||
class ConsoleView { +update(event, data) }
|
||||
class Command {
|
||||
<<interface>>
|
||||
+execute()
|
||||
+undo()
|
||||
}
|
||||
class MoveCommand {
|
||||
-Player player
|
||||
-Cell target_cell
|
||||
-Cell previous_cell
|
||||
+execute()
|
||||
+undo()
|
||||
}
|
||||
class Player {
|
||||
-Cell current_cell
|
||||
+move_to(cell)
|
||||
}
|
||||
|
||||
MazeBuilder <|.. TextFileMazeBuilder
|
||||
TextFileMazeBuilder ..> Maze : creates
|
||||
Maze o-- Cell
|
||||
PathFindingStrategy <|.. BFSStrategy
|
||||
PathFindingStrategy <|.. DFSStrategy
|
||||
PathFindingStrategy <|.. AStarStrategy
|
||||
MazeSolver --> Maze
|
||||
MazeSolver --> PathFindingStrategy
|
||||
MazeSolver --> SearchStats
|
||||
MazeSolver --> Observer
|
||||
Observer <|.. ConsoleView
|
||||
Command <|.. MoveCommand
|
||||
MoveCommand --> Player
|
||||
Player --> Cell
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Ключевые фрагменты реализации
|
||||
|
||||
### Смена алгоритма через Strategy
|
||||
|
||||
```python
|
||||
solver = MazeSolver(maze)
|
||||
solver.set_strategy(BFSStrategy())
|
||||
stats_bfs = solver.solve()
|
||||
|
||||
solver.set_strategy(AStarStrategy()) # меняем алгоритм — одна строка
|
||||
stats_astar = solver.solve()
|
||||
```
|
||||
|
||||
### Подписка Observer
|
||||
|
||||
```python
|
||||
view = ConsoleView()
|
||||
solver.add_observer(view)
|
||||
solver.solve() # ConsoleView автоматически получит событие path_found
|
||||
```
|
||||
|
||||
### Команда с отменой
|
||||
|
||||
```python
|
||||
player = Player(maze.start)
|
||||
cmd = MoveCommand(player, next_cell)
|
||||
cmd.execute() # игрок перешёл
|
||||
cmd.undo() # игрок вернулся обратно
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Экспериментальная часть
|
||||
|
||||
### Параметры эксперимента
|
||||
|
||||
| Параметр | Значение |
|
||||
|---|---|
|
||||
| Повторений на замер | 7 |
|
||||
| Алгоритмы | BFS, DFS, A* |
|
||||
| Метрики | время (мс), посещено клеток, длина пути |
|
||||
|
||||
### Тестовые лабиринты
|
||||
|
||||
| Название | Размер | Особенность |
|
||||
|---|---|---|
|
||||
| small_10x10 | 10×10 | Маленький, простой путь |
|
||||
| medium_50x50 | 50×50 | Средний, тупики (28% стен) |
|
||||
| large_100x100 | 100×100 | Большой (30% стен) |
|
||||
| open_50x50 | 50×50 | Без внутренних стен |
|
||||
| no_exit_20x20 | 20×20 | Выход недостижим |
|
||||
|
||||
---
|
||||
|
||||
## Результаты
|
||||
|
||||
### Таблица средних значений
|
||||
|
||||
| Лабиринт | Алгоритм | Время (мс) | Посещено клеток | Длина пути |
|
||||
|---|---|---|---|---|
|
||||
| small_10x10 | BFS | 0.094 | 54 | 15 |
|
||||
| small_10x10 | DFS | 0.059 | 33 | 33 |
|
||||
| small_10x10 | A* | 0.078 | 36 | 15 |
|
||||
| medium_50x50 | BFS | 2.446 | 1639 | 95 |
|
||||
| medium_50x50 | DFS | 1.480 | 1063 | 185 |
|
||||
| medium_50x50 | A* | 1.528 | 588 | 95 |
|
||||
| large_100x100 | BFS | 9.891 | 6564 | — |
|
||||
| large_100x100 | DFS | 9.057 | 6564 | — |
|
||||
| large_100x100 | A* | 17.578 | 6564 | — |
|
||||
| open_50x50 | BFS | 3.296 | 2304 | 95 |
|
||||
| open_50x50 | DFS | 1.830 | 1223 | 1129 |
|
||||
| open_50x50 | A* | 5.566 | 2304 | 95 |
|
||||
| no_exit_20x20 | BFS | 0.368 | 260 | — |
|
||||
| no_exit_20x20 | DFS | 0.343 | 260 | — |
|
||||
| no_exit_20x20 | A* | 0.607 | 260 | — |
|
||||
|
||||
*«—» — путь не найден, все доступные клетки исчерпаны*
|
||||
|
||||
### Визуализация
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
## Анализ эффективности алгоритмов
|
||||
|
||||
### BFS — гарантия кратчайшего пути
|
||||
|
||||
BFS находит **оптимальный путь** во всех случаях: 15 шагов на small, 95 на medium. Достигается за счёт обхода волнами — клетки посещаются в порядке удалённости от старта. Платой является высокое число посещённых клеток: 1639 на medium против 1063 у DFS. Это теоретически ожидаемо: BFS — O(V+E), где V — все вершины.
|
||||
|
||||
### DFS — скорость за счёт качества пути
|
||||
|
||||
DFS работает быстрее по времени (1.480 мс против 2.446 мс у BFS на medium), но путь длиннее в 1.9 раза (185 против 95 шагов). На открытом лабиринте без стен разрыв катастрофический: **1129 шагов против 95 у BFS**. Это классическая демонстрация того, что DFS уходит в глубину по первому попавшемуся пути, не оглядываясь на альтернативы.
|
||||
|
||||
### A* — лучший баланс при наличии препятствий
|
||||
|
||||
A* с манхэттенской эвристикой посетил всего **588 клеток** на medium против 1639 у BFS — в 2.8 раза меньше — при одинаковой длине пути (95 шагов). Эвристика `|x1−x2| + |y1−y2|` направляет поиск к выходу и отсекает заведомо невыгодные направления.
|
||||
|
||||
На открытом лабиринте без стен A* проигрывает по времени (5.566 мс против 3.296 мс у BFS): эвристика пересчитывается для каждой из 2304 клеток, а отсекать нечего — все пути одинаково перспективны.
|
||||
|
||||
### Большой лабиринт (100×100) — путь не найден
|
||||
|
||||
При плотности стен 30% выход оказался недостижим. Все три алгоритма исчерпали все 6564 доступные клетки. Корректность обработки этого случая — важный результат: каждый алгоритм возвращает пустой список, а не зависает.
|
||||
|
||||
### Лабиринт без выхода (20×20)
|
||||
|
||||
Все алгоритмы обошли все 260 доступных клеток и корректно вернули пустой путь. A* в этом сценарии чуть медленнее (0.607 мс против 0.368 мс у BFS) — приоритетная очередь имеет накладные расходы O(log n) на каждую операцию.
|
||||
|
||||
---
|
||||
|
||||
## Выводы
|
||||
|
||||
### Эффективность алгоритмов в разных сценариях
|
||||
|
||||
| Задача | Рекомендация | Обоснование |
|
||||
|---|---|---|
|
||||
| Кратчайший путь | BFS или A* | Оба гарантируют оптимум |
|
||||
| Большой лабиринт с препятствиями | A* | В 2–3 раза меньше посещённых клеток |
|
||||
| Открытое пространство | BFS | A* теряет преимущество без отсечений |
|
||||
| Нужен любой путь быстро | DFS | Меньше клеток, меньше накладных расходов |
|
||||
| Недостижимый выход | Любой | Все алгоритмы корректно завершаются |
|
||||
|
||||
### Применимость паттернов
|
||||
|
||||
**Strategy** — самый ценный паттерн в данной задаче. Именно он позволяет запускать три алгоритма через единый интерфейс в цикле бенчмарка без дублирования кода. Добавление четвёртого алгоритма (Dijkstra) займёт ~30 строк без правок в `MazeSolver` или `benchmark.py`.
|
||||
|
||||
**Builder** оправдал себя при добавлении пяти разных лабиринтов: клиентский код (`benchmark.py`) не менялся, только передавался другой файл. Без Builder парсинг был бы размазан по всему коду.
|
||||
|
||||
**Observer** отделил вывод от логики: в бенчмарке `ConsoleView` не подключается вовсе, чтобы не засорять вывод. В интерактивном режиме подключается одной строкой.
|
||||
|
||||
**Command** демонстрирует принцип undo/redo: без него отмена хода требовала бы хранения копии состояния снаружи объекта `Player`. С Command история инкапсулирована в стеке команд.
|
||||
|
||||
### Общий вывод
|
||||
|
||||
ООП и паттерны проектирования сделали код модульным и расширяемым. Каждый класс решает одну задачу. Изменение любого компонента (алгоритм, формат файла, интерфейс) не ломает остальные части программы — это и есть практическая ценность паттернов GoF.
|
||||
Loading…
Reference in New Issue
Block a user