diff --git a/victorovaas/lab2/dead.txt b/victorovaas/lab2/dead.txt new file mode 100644 index 00000000..5f30fecd --- /dev/null +++ b/victorovaas/lab2/dead.txt @@ -0,0 +1,20 @@ +#################### +#S # +# # +# # +# # +# ######### # +# # # +# # # +# # # +# # # +# # # +# # # +# # # +# # # +# # # +# # +# # +# # +# E# +#################### diff --git a/victorovaas/lab2/docs/data/dead_path_graph.png b/victorovaas/lab2/docs/data/dead_path_graph.png new file mode 100644 index 00000000..5299126d Binary files /dev/null and b/victorovaas/lab2/docs/data/dead_path_graph.png differ diff --git a/victorovaas/lab2/docs/data/dead_time_graph.png b/victorovaas/lab2/docs/data/dead_time_graph.png new file mode 100644 index 00000000..64a1d4e5 Binary files /dev/null and b/victorovaas/lab2/docs/data/dead_time_graph.png differ diff --git a/victorovaas/lab2/docs/data/dead_visited_graph.png b/victorovaas/lab2/docs/data/dead_visited_graph.png new file mode 100644 index 00000000..3d169b1d Binary files /dev/null and b/victorovaas/lab2/docs/data/dead_visited_graph.png differ diff --git a/victorovaas/lab2/docs/data/empty_path_graph.png b/victorovaas/lab2/docs/data/empty_path_graph.png new file mode 100644 index 00000000..a9d7dcd6 Binary files /dev/null and b/victorovaas/lab2/docs/data/empty_path_graph.png differ diff --git a/victorovaas/lab2/docs/data/empty_time_graph.png b/victorovaas/lab2/docs/data/empty_time_graph.png new file mode 100644 index 00000000..aa5469f9 Binary files /dev/null and b/victorovaas/lab2/docs/data/empty_time_graph.png differ diff --git a/victorovaas/lab2/docs/data/empty_visited_graph.png b/victorovaas/lab2/docs/data/empty_visited_graph.png new file mode 100644 index 00000000..c7388d60 Binary files /dev/null and b/victorovaas/lab2/docs/data/empty_visited_graph.png differ diff --git a/victorovaas/lab2/docs/data/maze_experiments.csv b/victorovaas/lab2/docs/data/maze_experiments.csv new file mode 100644 index 00000000..d10c8143 --- /dev/null +++ b/victorovaas/lab2/docs/data/maze_experiments.csv @@ -0,0 +1,13 @@ +Лабиринт,Стратегия,Время(мс),Посещено клеток,Длина пути +Простой,BFS,0.017,11.0,6.0 +Простой,DFS,0.017,9.0,8.0 +Простой,A*,0.024,9.0,6.0 +С тупиками,BFS,0.355,306.0,35.0 +С тупиками,DFS,0.18,198.0,81.0 +С тупиками,A*,0.407,225.0,35.0 +Пустой,BFS,2.873,2304.0,95.0 +Пустой,DFS,8.03,2304.0,1129.0 +Пустой,A*,4.278,2304.0,95.0 +Без выхода,BFS,0.003,1.0,нет пути +Без выхода,DFS,0.002,1.0,нет пути +Без выхода,A*,0.014,1.0,нет пути diff --git a/victorovaas/lab2/docs/data/maze_table_results.png b/victorovaas/lab2/docs/data/maze_table_results.png new file mode 100644 index 00000000..f24630db Binary files /dev/null and b/victorovaas/lab2/docs/data/maze_table_results.png differ diff --git a/victorovaas/lab2/docs/data/noexit_time_graph.png b/victorovaas/lab2/docs/data/noexit_time_graph.png new file mode 100644 index 00000000..8d21fc2e Binary files /dev/null and b/victorovaas/lab2/docs/data/noexit_time_graph.png differ diff --git a/victorovaas/lab2/docs/data/noexit_visited_graph.png b/victorovaas/lab2/docs/data/noexit_visited_graph.png new file mode 100644 index 00000000..9541be62 Binary files /dev/null and b/victorovaas/lab2/docs/data/noexit_visited_graph.png differ diff --git a/victorovaas/lab2/docs/data/simple_path_graph.png b/victorovaas/lab2/docs/data/simple_path_graph.png new file mode 100644 index 00000000..9042b6cf Binary files /dev/null and b/victorovaas/lab2/docs/data/simple_path_graph.png differ diff --git a/victorovaas/lab2/docs/data/simple_time_graph.png b/victorovaas/lab2/docs/data/simple_time_graph.png new file mode 100644 index 00000000..9f355913 Binary files /dev/null and b/victorovaas/lab2/docs/data/simple_time_graph.png differ diff --git a/victorovaas/lab2/docs/data/simple_visited_graph.png b/victorovaas/lab2/docs/data/simple_visited_graph.png new file mode 100644 index 00000000..746248a0 Binary files /dev/null and b/victorovaas/lab2/docs/data/simple_visited_graph.png differ diff --git a/victorovaas/lab2/docs/lab2_report.ipynb b/victorovaas/lab2/docs/lab2_report.ipynb new file mode 100644 index 00000000..b74a85e4 --- /dev/null +++ b/victorovaas/lab2/docs/lab2_report.ipynb @@ -0,0 +1,237 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "bdef001e", + "metadata": {}, + "source": [ + "# Отчёт \n", + "## Поиск выхода из лабиринта: применение паттернов проектирования\n", + "\n", + "**Студент:** Викторова А.С.\n", + "**Группа:** 429\n", + "**Дата:** 03.09.2026" + ] + }, + { + "cell_type": "markdown", + "id": "21f948a4", + "metadata": {}, + "source": [ + "## Введение\n", + "\n", + "### О чём это работа\n", + "В данной работе реализуется программа для поиска выхода из лабиринта с применением паттернов проектирования. Поддерживаются три алгоритма поиска пути: BFS, DFS и A*.\n", + "\n", + "### Цель работы\n", + "Разработать гибкую, расширяемую программу для загрузки лабиринта из файла, поиска пути от старта до выхода с возможностью выбора алгоритма, визуализации процесса и экспериментального сравнения алгоритмов. Применить минимум 3 паттерна проектирования.\n", + "\n", + "### Задачи\n", + "1. Реализовать модель лабиринта (классы Cell, Maze)\n", + "2. Реализовать загрузку лабиринта из файла (паттерн Builder)\n", + "3. Реализовать алгоритмы поиска пути (паттерн Strategy): BFS, DFS, A*\n", + "4. Реализовать класс-оркестратор MazeSolver со сбором статистики\n", + "5. Реализовать визуализацию (паттерн Observer) и пошаговое управление (паттерн Command)\n", + "6. Провести эксперименты на лабиринтах разной сложности\n", + "7. Сравнить результаты и сделать выводы\n" + ] + }, + { + "cell_type": "markdown", + "id": "cf1dc2ba", + "metadata": {}, + "source": [ + "## Часть 1. Паттерны проектирования\n", + "\n", + "### Использованные паттерны\n", + "\n", + "| Паттерн | Назначение | Реализация |\n", + "|---------|------------|------------|\n", + "| Builder | Создание лабиринта из файла | TextFileMazeBuilder |\n", + "| Strategy | Семейство алгоритмов поиска | BFSStrategy, DFSStrategy, AStarStrategy |\n", + "| Observer | Уведомление о событиях | ConsoleView |\n", + "| Command | Отмена ходов | MoveCommand |\n" + ] + }, + { + "cell_type": "markdown", + "id": "55cef4b9", + "metadata": {}, + "source": [ + "## Часть 2. Реализация\n", + "\n", + "### 2.1 Модель лабиринта\n", + "\n", + "**Класс Cell** - клетка лабиринта\n", + "- Поля: x, y, is_wall, is_start, is_exit\n", + "- Метод: is_passable() - возвращает True, если не стена\n", + "\n", + "**Класс Maze** - лабиринт\n", + "- Поля: width, height, cells[][], start, exit\n", + "- Методы: get_cell(x, y), get_neighbors(cell)\n", + "\n", + "### 2.2 Загрузка лабиринта (Builder)\n", + "\n", + "**TextFileMazeBuilder**\n", + "- Читает файл с символами (# - стена, пробел - проход, S - старт, E - выход)\n", + "- Создаёт клетки с нужными флагами\n", + "- Возвращает готовый Maze\n", + "\n", + "### 2.3 Алгоритмы поиска (Strategy)\n", + "\n", + "**Интерфейс PathFindingStrategy**\n", + "- Метод: find_path(maze, start, exit) возвращает (путь, количество_посещённых)\n", + "\n", + "**BFSStrategy** - поиск в ширину (очередь)\n", + "- Гарантирует кратчайший путь\n", + "\n", + "**DFSStrategy** - поиск в глубину (стек)\n", + "- Быстрый, но не гарантирует кратчайший путь\n", + "\n", + "**AStarStrategy** - A* (приоритетная очередь)\n", + "- Использует эвристику (манхэттенское расстояние)\n", + "\n", + "### 2.4 Оркестратор\n", + "\n", + "**MazeSolver**\n", + "- Поля: maze, strategy\n", + "- Методы: set_strategy(), solve() → SearchStats\n", + "\n", + "**SearchStats**\n", + "- Поля: path, time_ms, visited_count, path_length" + ] + }, + { + "cell_type": "markdown", + "id": "5c9bd0d2", + "metadata": {}, + "source": [ + "## Часть 3. Эксперименты\n", + "\n", + "### 3.1 Условия\n", + "\n", + "| Параметр | Значение |\n", + "|----------|----------|\n", + "| Повторений | 5 |\n", + "| Алгоритмы | BFS, DFS, A* |\n", + "| Лабиринты | Простой (10x10), С тупиками (50x50), Пустой (100x100), Без выхода |\n", + "\n", + "### 3.2 Тестовые лабиринты\n", + "\n", + "| Лабиринт | Размер | Характеристика |\n", + "|----------|--------|----------------|\n", + "| Простой | 10x10 | Прямой путь от старта к выходу |\n", + "| С тупиками | 20x20 | Много тупиков, запутанный |\n", + "| Пустой | 50x50 | Без стен (максимальная производительность) |\n", + "| Без выхода | 10x10 | Выход отгорожен стенами |\n", + "\n", + "### 3.3 Результаты экспериментов\n", + "\n", + "| Лабиринт | Стратегия | Время (мс) | Посещено клеток | Длина пути |\n", + "|----------|-----------|------------|-----------------|------------|\n", + "| Простой (10x10) | BFS | 0.020 | 11 | 6 |\n", + "| Простой (10x10) | DFS | 0.012 | 9 | 8 |\n", + "| Простой (10x10) | A* | 0.020 | 9 | 6 |\n", + "| С тупиками (20x20) | BFS | 0.492 | 306 | 35 |\n", + "| С тупиками (20x20) | DFS | 0.234 | 198 | 81 |\n", + "| С тупиками (20x20) | A* | 0.456 | 225 | 35 |\n", + "| Пустой (50x50) | BFS | 3.486 | 2304 | 95 |\n", + "| Пустой (50x50) | DFS | 10.452 | 2304 | 1129 |\n", + "| Пустой (50x50) | A* | 5.743 | 2304 | 95 |\n", + "| Без выхода | BFS | 0.010 | 1 | нет пути |\n", + "| Без выхода | DFS | 0.003 | 1 | нет пути |\n", + "| Без выхода | A* | 0.004 | 1 | нет пути |\n", + "\n", + "### 3.4 Графики\n", + "\n", + "#### Простой лабиринт (10x10)\n", + "\n", + "![Время](data/simple_time_graph.png)\n", + "![Посещено](data/simple_visited_graph.png)\n", + "![Длина пути](data/simple_path_graph.png)\n", + "\n", + "#### Лабиринт с тупиками (20x20)\n", + "\n", + "![Время](data/dead_time_graph.png)\n", + "![Посещено](data/dead_visited_graph.png)\n", + "![Длина пути](data/dead_path_graph.png)\n", + "\n", + "#### Пустой лабиринт (50x50)\n", + "\n", + "![Время](data/empty_time_graph.png)\n", + "![Посещено](data/empty_visited_graph.png)\n", + "![Длина пути](data/empty_path_graph.png)\n", + "\n", + "#### Лабиринт без выхода\n", + "\n", + "![Время](data/noexit_time_graph.png)\n", + "![Посещено](data/noexit_visited_graph.png)\n", + "\n", + "### 3.5 Общая таблица результатов\n", + "\n", + "![Таблица](data/maze_table_results.png)\n", + "\n", + "### 3.6 Анализ результатов\n", + "\n", + "**Простой лабиринт (10x10):**\n", + "- BFS и A* нашли кратчайший путь (6 шагов)\n", + "- DFS нашёл более длинный путь (8 шагов), но был быстрее всех\n", + "\n", + "**Лабиринт с тупиками (20x20):**\n", + "- BFS и A* нашли кратчайший путь (35 шагов)\n", + "- DFS нашёл очень длинный путь (81 шаг), так как ушёл в глубину по тупикам\n", + "\n", + "**Пустой лабиринт (50x50):**\n", + "- BFS и A* нашли кратчайший путь (95 шагов)\n", + "- DFS нашёл очень длинный путь (1129 шагов)\n", + "\n", + "**Лабиринт без выхода:**\n", + "- Все алгоритмы посетили только стартовую клетку (1) и вернули \"нет пути\"\n", + "\n", + "### 3.7 Сравнение алгоритмов\n", + "\n", + "| Алгоритм | Кратчайший путь | Скорость | Память | Когда использовать |\n", + "|----------|-----------------|----------|--------|-------------------|\n", + "| BFS | Да | Средняя | Много | Нужен гарантированно кратчайший путь |\n", + "| DFS | Нет | Быстрая | Мало | Важна скорость, не важна длина пути |\n", + "| A* | Да | Быстрая | Средне | Большие лабиринты, есть эвристика |\n", + "\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "id": "e687a8ee", + "metadata": {}, + "source": [ + "## Заключение\n", + "\n", + "### Выводы\n", + "\n", + "1. **BFS** гарантирует кратчайший путь, но медленнее на больших лабиринтах\n", + "2. **DFS** самый быстрый, но путь может быть очень длинным\n", + "3. **A*** - лучший компромисс: находит кратчайший путь и работает быстро\n", + "\n", + "### Рекомендация\n", + "\n", + "Для поиска выхода из лабиринта рекомендуется использовать **A*** - он сочетает скорость и оптимальность.\n", + "\n", + "### Как паттерны помогли\n", + "\n", + "| Изменение | Без паттернов | С паттернами |\n", + "|-----------|---------------|--------------|\n", + "| Добавить новый алгоритм | Изменить MazeSolver | Создать новую стратегию |\n", + "| Сменить визуализацию | Переписать MazeSolver | Добавить новый Observer |\n", + "\n", + "**Итог:** Паттерны сделали код гибким и расширяемым." + ] + } + ], + "metadata": { + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/victorovaas/lab2/empty.txt b/victorovaas/lab2/empty.txt new file mode 100644 index 00000000..c83b6cdc --- /dev/null +++ b/victorovaas/lab2/empty.txt @@ -0,0 +1,50 @@ +################################################## +#S # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# # +# E# +################################################## diff --git a/victorovaas/experiments.py b/victorovaas/lab2/experiments.py similarity index 100% rename from victorovaas/experiments.py rename to victorovaas/lab2/experiments.py diff --git a/victorovaas/lab2/lab2/maze_solver.py b/victorovaas/lab2/lab2/maze_solver.py new file mode 100644 index 00000000..c22b789e --- /dev/null +++ b/victorovaas/lab2/lab2/maze_solver.py @@ -0,0 +1,367 @@ +from abc import ABC, abstractmethod +from collections import deque +import heapq +import time +import os + +class Cell: + def __init__(self, x, y): + self.x = x + self.y = y + self.is_wall = False + self.is_start = False + self.is_exit = False + + def is_passable(self): + return not self.is_wall + + def __repr__(self): + return f"Cell({self.x},{self.y})" + + +class Maze: + def __init__(self, width, height): + self.width = width + self.height = height + self.cells = [] + self.start = None + self.exit = None + + for y in range(height): + row = [] + for x in range(width): + row.append(Cell(x, y)) + self.cells.append(row) + + 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): + neighbors = [] + for dx, dy in [(0, -1), (0, 1), (-1, 0), (1, 0)]: + nx, ny = cell.x + dx, cell.y + dy + neighbor = self.get_cell(nx, ny) + if neighbor and neighbor.is_passable(): + neighbors.append(neighbor) + return neighbors + + +class TextFileMazeBuilder: + def build_from_file(self, filename): + with open(filename, 'r') as f: + lines = [line.rstrip() for line in f.readlines()] + + height = len(lines) + width = len(lines[0]) + maze = Maze(width, height) + + for y, line in enumerate(lines): + for x, ch in enumerate(line): + cell = maze.get_cell(x, y) + if ch == '#': + cell.is_wall = True + elif ch == 'S': + maze.start = cell + cell.is_start = True + elif ch == 'E': + maze.exit = cell + cell.is_exit = True + + return maze + + +class PathFindingStrategy(ABC): + @abstractmethod + def find_path(self, maze, start, exit): + pass + + +class BFSStrategy(PathFindingStrategy): + def find_path(self, maze, start, exit): + if not start or not exit: + return [], 0 + + queue = deque([(start, [start])]) + visited = {start} + + while queue: + current, path = queue.popleft() + if current == exit: + return path, len(visited) + + for neighbor in maze.get_neighbors(current): + if neighbor not in visited: + visited.add(neighbor) + queue.append((neighbor, path + [neighbor])) + + return [], len(visited) + + +class DFSStrategy(PathFindingStrategy): + def find_path(self, maze, start, exit): + if not start or not exit: + return [], 0 + + stack = [(start, [start])] + visited = {start} + + while stack: + current, path = stack.pop() + if current == exit: + return path, len(visited) + + for neighbor in maze.get_neighbors(current): + if neighbor not in visited: + visited.add(neighbor) + stack.append((neighbor, path + [neighbor])) + + return [], len(visited) + + +class AStarStrategy(PathFindingStrategy): + def _heuristic(self, a, b): + return abs(a.x - b.x) + abs(a.y - b.y) + + def find_path(self, maze, start, exit): + if not start or not exit: + return [], 0 + + heap = [(self._heuristic(start, exit), 0, start, [start])] + g_score = {start: 0} + visited = set() + counter = 1 + + while heap: + _, _, current, path = heapq.heappop(heap) + + if current in visited: + continue + + visited.add(current) + + if current == exit: + return path, len(visited) + + for neighbor in maze.get_neighbors(current): + tentative_g = g_score[current] + 1 + if neighbor not in g_score or tentative_g < g_score[neighbor]: + g_score[neighbor] = tentative_g + f = tentative_g + self._heuristic(neighbor, exit) + heapq.heappush(heap, (f, counter, neighbor, path + [neighbor])) + counter += 1 + + return [], len(visited) + + +class SearchStats: + def __init__(self, path, time_ms, visited_count): + self.path = path + self.time_ms = time_ms + self.visited_count = visited_count + self.path_length = len(path) if path else 0 + + +class MazeSolver: + def __init__(self, maze, strategy=None): + self.maze = maze + self.strategy = strategy + self.observers = [] + + def attach(self, observer): + self.observers.append(observer) + + def detach(self, observer): + self.observers.remove(observer) + + def notify(self, event, data=None): + for observer in self.observers: + observer.update(event, data) + + def set_strategy(self, strategy): + self.strategy = strategy + + def solve(self): + if self.strategy is None: + raise ValueError("Стратегия не установлена") + self.notify("search_started") + + start_time = time.perf_counter() + path, visited_count = self.strategy.find_path(self.maze, self.maze.start, self.maze.exit) + end_time = time.perf_counter() + time_ms = (end_time - start_time) * 1000 + + self.notify("search_finished", time_ms) + self.notify("path_found", path) + + return SearchStats(path, time_ms, visited_count) + +class Observer(ABC): + + @abstractmethod + def update(self, event, data=None): + pass + +class ConsoleView(Observer): + + def __init__(self): + self.events = [] + + def update(self, event, data=None): + self.events.append((event, data)) + + if event == "maze_loaded": + print("[Событие] Лфбирин загружен") + elif event == "path_found": + print(f"[Событие] Путь найден! Длина: {len(data) if data else 0}") + elif event == "search_started": + print(f"[Событие] Поиск завершён. Время: {data:.3f}мс" if data else "[Событие] Поиск завершён") + elif event == "mpve": + print(f"[Событие] Игрок переместился в {data}") + elif event == "undo": + print("[Событие] Отмена последнего хода") + + def render(self,maze, player=None, path=None): + + os.system('cls' if os.name == 'nt' else 'clear') + + print("Лабиринт") + + for y in range(maze.height): + row = "" + for x in range(maze.width): + cell = maze.get_cell(x,y) + + if player and cell == player.current_cell: + row += "p " #игрок + elif path and cell in path: + row += "* " #путь + elif cell.is_wall: + row += "# " #стена + elif cell.is_start: + row += "S " #старт + elif cell.is_exit: + row += "E " #выход + else: + row += ". " #прозод + print(row) + + print("Управление: W/A/S/D - движение, U - отмена, Q - выход") + +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 + self.start_cell = start_cell + + def move_to(self, cell): + self.current_cell = cell + + def resent(self): + self.current_cell = self.start_cell + + def __repr__(self): + return f"Player at ({self.current_cell.x}, {self.current_cell.y})" + +class MoveCommand(Command): + + def __init__(self, player, new_cell, view): + self.player = player + self.new_cell = new_cell + self.old_cell = player.current_cell + self.view = view + + def execute(self): + self.player.move_to(self.new_cell) + self.view.update("undo", None) + + def undo(self): + self.player.move_to(self.old_cell) + self.view.update("undo",None) + +class GameController: + + def __init__(self, maze, view): + self.maze = maze + self.view = view + self.player = Player(maze.start) + self.command_history = [] + + def get_cell_in_direction(self, direction): + + x, y = self.player.current_cell.x, self.player.current_cell.y + + if direction == 'w': + y -= 1 + elif direction == 's': + y += 1 + elif direction == 'a': + x -= 1 + elif direction == 'd': + x += 1 + else: + return None + + return self.maze.get_cell(x, y) + + def try_move(self, direction): + + new_cell = self.get_cell_in_direction(direction) + + if new_cell and new_cell.is_passable(): + command = MoveCommand(self.player, new_cell, self.view) + command.execute() + self.command_history.append(command) + + if new_cell.is_exit: + self.view.update("path_found", []) + print("Вы нашли выход.") + return True + else: + print("Невозможно пройти - стена") + return False + + def undo(self): + + if self.command_history: + command = self.command_history.pop() + command.undo() + else: + print("Нечего отменять") + + def visualize_path(self, path): + self.view.render(self.maze, self.player, path) + + def run_manual_mode(self): + + while True: + self.view.render(self.maze, self.player) + + command = input("Введите команду: ").lower().strip() + + if command in ['w', 'a', 's', 'd']: + self.try_move(command) + elif command == 'u': + self.undo() + elif command == 'q': + print('Выход из игры') + break + else: + print("Неизвестная команда. Используйте: W/A/S/D - движение, U - отмена, Q - выход") + + + + + + diff --git a/victorovaas/make_graphs.py b/victorovaas/lab2/make_graphs.py similarity index 100% rename from victorovaas/make_graphs.py rename to victorovaas/lab2/make_graphs.py diff --git a/victorovaas/lab2/make_lab2_plots.py b/victorovaas/lab2/make_lab2_plots.py new file mode 100644 index 00000000..6b96ed1c --- /dev/null +++ b/victorovaas/lab2/make_lab2_plots.py @@ -0,0 +1,162 @@ +import matplotlib.pyplot as plt +import os + +os.makedirs('lab2/docs/data', exist_ok=True) + +algorithms = ['BFS', 'DFS', 'A*'] + + +simple_time = [0.020, 0.012, 0.020] +simple_visited = [11, 9, 9] +simple_path = [6, 8, 6] + +fig, ax = plt.subplots(figsize=(8, 5)) +bars = ax.bar(algorithms, simple_time, color=['#3498db', '#e74c3c', '#2ecc71']) +ax.set_ylabel('Время (мс)') +ax.set_title('Время выполнения (простой лабиринт 10x10)') +for bar, val in zip(bars, simple_time): + ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.001, f'{val:.3f}', ha='center', va='bottom') +plt.savefig('docs/data/simple_time_graph.png', dpi=150, bbox_inches='tight') +plt.close() + +fig, ax = plt.subplots(figsize=(8, 5)) +bars = ax.bar(algorithms, simple_visited, color=['#3498db', '#e74c3c', '#2ecc71']) +ax.set_ylabel('Количество клеток') +ax.set_title('Посещённые клетки (простой лабиринт)') +for bar, val in zip(bars, simple_visited): + ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.3, str(val), ha='center', va='bottom') +plt.savefig('docs/data/simple_visited_graph.png', dpi=150, bbox_inches='tight') +plt.close() + +fig, ax = plt.subplots(figsize=(8, 5)) +bars = ax.bar(algorithms, simple_path, color=['#3498db', '#e74c3c', '#2ecc71']) +ax.set_ylabel('Длина пути (шагов)') +ax.set_title('Длина найденного пути (простой лабиринт)') +for bar, val in zip(bars, simple_path): + ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.3, str(val), ha='center', va='bottom') +plt.savefig('docs/data/simple_path_graph.png', dpi=150, bbox_inches='tight') +plt.close() + + +dead_time = [0.492, 0.234, 0.456] +dead_visited = [306, 198, 225] +dead_path = [35, 81, 35] + +fig, ax = plt.subplots(figsize=(8, 5)) +bars = ax.bar(algorithms, dead_time, color=['#3498db', '#e74c3c', '#2ecc71']) +ax.set_ylabel('Время (мс)') +ax.set_title('Время выполнения (лабиринт с тупиками)') +for bar, val in zip(bars, dead_time): + ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.01, f'{val:.3f}', ha='center', va='bottom') +plt.savefig('docs/data/dead_time_graph.png', dpi=150, bbox_inches='tight') +plt.close() + +fig, ax = plt.subplots(figsize=(8, 5)) +bars = ax.bar(algorithms, dead_visited, color=['#3498db', '#e74c3c', '#2ecc71']) +ax.set_ylabel('Количество клеток') +ax.set_title('Посещённые клетки (лабиринт с тупиками)') +for bar, val in zip(bars, dead_visited): + ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 10, str(val), ha='center', va='bottom') +plt.savefig('docs/data/dead_visited_graph.png', dpi=150, bbox_inches='tight') +plt.close() + +fig, ax = plt.subplots(figsize=(8, 5)) +bars = ax.bar(algorithms, dead_path, color=['#3498db', '#e74c3c', '#2ecc71']) +ax.set_ylabel('Длина пути (шагов)') +ax.set_title('Длина найденного пути (лабиринт с тупиками)') +for bar, val in zip(bars, dead_path): + ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 3, str(val), ha='center', va='bottom') +plt.savefig('docs/data/dead_path_graph.png', dpi=150, bbox_inches='tight') +plt.close() + + +empty_time = [3.486, 10.452, 5.743] +empty_visited = [2304, 2304, 2304] +empty_path = [95, 1129, 95] + +fig, ax = plt.subplots(figsize=(8, 5)) +bars = ax.bar(algorithms, empty_time, color=['#3498db', '#e74c3c', '#2ecc71']) +ax.set_ylabel('Время (мс)') +ax.set_title('Время выполнения (пустой лабиринт 50x50)') +for bar, val in zip(bars, empty_time): + ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.3, f'{val:.3f}', ha='center', va='bottom') +plt.savefig('docs/data/empty_time_graph.png', dpi=150, bbox_inches='tight') +plt.close() + +fig, ax = plt.subplots(figsize=(8, 5)) +bars = ax.bar(algorithms, empty_visited, color=['#3498db', '#e74c3c', '#2ecc71']) +ax.set_ylabel('Количество клеток') +ax.set_title('Посещённые клетки (пустой лабиринт)') +for bar, val in zip(bars, empty_visited): + ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 50, str(val), ha='center', va='bottom') +plt.savefig('docs/data/empty_visited_graph.png', dpi=150, bbox_inches='tight') +plt.close() + +fig, ax = plt.subplots(figsize=(8, 5)) +bars = ax.bar(algorithms, empty_path, color=['#3498db', '#e74c3c', '#2ecc71']) +ax.set_ylabel('Длина пути (шагов)') +ax.set_title('Длина найденного пути (пустой лабиринт)') +for bar, val in zip(bars, empty_path): + ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 50, str(val), ha='center', va='bottom') +plt.savefig('docs/data/empty_path_graph.png', dpi=150, bbox_inches='tight') +plt.close() + + +noexit_time = [0.010, 0.003, 0.004] +noexit_visited = [1, 1, 1] + +fig, ax = plt.subplots(figsize=(8, 5)) +bars = ax.bar(algorithms, noexit_time, color=['#3498db', '#e74c3c', '#2ecc71']) +ax.set_ylabel('Время (мс)') +ax.set_title('Время выполнения (лабиринт без выхода)') +for bar, val in zip(bars, noexit_time): + ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.0005, f'{val:.3f}', ha='center', va='bottom') +plt.savefig('docs/data/noexit_time_graph.png', dpi=150, bbox_inches='tight') +plt.close() + +fig, ax = plt.subplots(figsize=(8, 5)) +bars = ax.bar(algorithms, noexit_visited, color=['#3498db', '#e74c3c', '#2ecc71']) +ax.set_ylabel('Количество клеток') +ax.set_title('Посещённые клетки (лабиринт без выхода)') +for bar, val in zip(bars, noexit_visited): + ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.05, str(val), ha='center', va='bottom') +plt.savefig('docs/data/noexit_visited_graph.png', dpi=150, bbox_inches='tight') +plt.close() + + +fig, ax = plt.subplots(figsize=(14, 8)) +ax.axis('off') + +table_data = [ + ['Лабиринт', 'Стратегия', 'Время (мс)', 'Посещено', 'Длина пути'], + ['Простой (10x10)', 'BFS', '0.020', '11', '6'], + ['Простой (10x10)', 'DFS', '0.012', '9', '8'], + ['Простой (10x10)', 'A*', '0.020', '9', '6'], + ['С тупиками (20x20)', 'BFS', '0.492', '306', '35'], + ['С тупиками (20x20)', 'DFS', '0.234', '198', '81'], + ['С тупиками (20x20)', 'A*', '0.456', '225', '35'], + ['Пустой (50x50)', 'BFS', '3.486', '2304', '95'], + ['Пустой (50x50)', 'DFS', '10.452', '2304', '1129'], + ['Пустой (50x50)', 'A*', '5.743', '2304', '95'], + ['Без выхода', 'BFS', '0.010', '1', 'нет пути'], + ['Без выхода', 'DFS', '0.003', '1', 'нет пути'], + ['Без выхода', 'A*', '0.004', '1', 'нет пути'], +] + +table = ax.table(cellText=table_data, loc='center', cellLoc='center', colWidths=[0.2, 0.13, 0.13, 0.13, 0.13]) +table.auto_set_font_size(False) +table.set_fontsize(10) +table.scale(1, 1.8) + +for i in range(5): + table[(0, i)].set_facecolor('#4472C4') + table[(0, i)].set_text_props(weight='bold', color='white') + +for i in range(1, len(table_data)): + if i % 2 == 1: + for j in range(5): + table[(i, j)].set_facecolor('#E8F0FE') + +plt.title('Результаты экспериментов по поиску пути в лабиринте', fontsize=14, fontweight='bold', pad=20) +plt.savefig('docs/data/maze_table_results.png', dpi=200, bbox_inches='tight', facecolor='white') +plt.close() diff --git a/victorovaas/lab2/maze_experiments.py b/victorovaas/lab2/maze_experiments.py new file mode 100644 index 00000000..3de62c6b --- /dev/null +++ b/victorovaas/lab2/maze_experiments.py @@ -0,0 +1,154 @@ +import time +import csv +import os +from lab2.maze_solver import TextFileMazeBuilder, BFSStrategy, DFSStrategy, AStarStrategy, MazeSolver + +def save_maze_to_file(maze, filename): + with open(filename, 'w') as f: + for row in maze: + f.write(''.join(row) + '\n') + +def run_test(maze_file, strategy_class): + builder = TextFileMazeBuilder() + maze = builder.build_from_file(maze_file) + solver = MazeSolver(maze, strategy_class) + + times = [] + visited = [] + path_len = [] + + for i in range(5): + stats = solver.solve() + times.append(stats.time_ms) + visited.append(stats.visited_count) + path_len.append(stats.path_length) + + return { + 'time': sum(times) / 5, + 'visited': sum(visited) / 5, + 'path': sum(path_len) / 5, + 'path_found': max(path_len) > 0 + } + +def main(): + + print("Эксперименты по поиску пути в лабиринте") + + + results = [] + + + print("\n1. Простой лабиринт (10x10)") + + + + simple = [ + "#######", + "#S #", + "# ### #", + "# E #", + "#######" + ] + with open('simple.txt', 'w') as f: + for line in simple: + f.write(line + '\n') + + for name, strategy in [('BFS', BFSStrategy()), ('DFS', DFSStrategy()), ('A*', AStarStrategy())]: + res = run_test('simple.txt', strategy) + print(f"{name}: время={res['time']:.3f}мс, посещено={res['visited']:.0f}, путь={res['path']:.0f}") + results.append(['Простой', name, round(res['time'], 3), round(res['visited'], 0), round(res['path'], 0)]) + + + print("\n2. Лабиринт с тупиками (20x20)") + + dead = [] + for y in range(20): + row = [] + for x in range(20): + if x == 0 or y == 0 or x == 19 or y == 19: + row.append('#') + elif (x == 5 and y > 5 and y < 15) or (y == 5 and x > 5 and x < 15): + row.append('#') + else: + row.append(' ') + dead.append(row) + dead[1][1] = 'S' + dead[18][18] = 'E' + + with open('dead.txt', 'w') as f: + for row in dead: + f.write(''.join(row) + '\n') + + for name, strategy in [('BFS', BFSStrategy()), ('DFS', DFSStrategy()), ('A*', AStarStrategy())]: + res = run_test('dead.txt', strategy) + print(f"{name}: время={res['time']:.3f}мс, посещено={res['visited']:.0f}, путь={res['path']:.0f}") + results.append(['С тупиками', name, round(res['time'], 3), round(res['visited'], 0), round(res['path'], 0)]) + + + print("\n3. Пустой лабиринт (50x50)") + + + empty = [] + for y in range(50): + row = [] + for x in range(50): + if x == 0 or y == 0 or x == 49 or y == 49: + row.append('#') + else: + row.append(' ') + empty.append(row) + empty[1][1] = 'S' + empty[48][48] = 'E' + + with open('empty.txt', 'w') as f: + for row in empty: + f.write(''.join(row) + '\n') + + for name, strategy in [('BFS', BFSStrategy()), ('DFS', DFSStrategy()), ('A*', AStarStrategy())]: + res = run_test('empty.txt', strategy) + print(f"{name}: время={res['time']:.3f}мс, посещено={res['visited']:.0f}, путь={res['path']:.0f}") + results.append(['Пустой', name, round(res['time'], 3), round(res['visited'], 0), round(res['path'], 0)]) + + + print("\n4. Лабиринт без выхода (10x10)") + + + noexit = [] + for y in range(10): + row = [] + for x in range(10): + if x == 0 or y == 0 or x == 9 or y == 9: + row.append('#') + else: + row.append('#') + noexit.append(row) + noexit[1][1] = 'S' + noexit[8][8] = 'E' + + with open('noexit.txt', 'w') as f: + for row in noexit: + f.write(''.join(row) + '\n') + + for name, strategy in [('BFS', BFSStrategy()), ('DFS', DFSStrategy()), ('A*', AStarStrategy())]: + try: + res = run_test('noexit.txt', strategy) + if res['path_found']: + print(f"{name}: путь найден! длина={res['path']:.0f}") + results.append(['Без выхода', name, round(res['time'], 3), round(res['visited'], 0), round(res['path'], 0)]) + else: + print(f"{name}: путь не найден (корректно)") + results.append(['Без выхода', name, round(res['time'], 3), round(res['visited'], 0), 'нет пути']) + except Exception as e: + print(f"{name}: ошибка - {e}") + results.append(['Без выхода', name, 0, 0, 'ошибка']) + + + os.makedirs('docs/data', exist_ok=True) + with open('docs/data/maze_experiments.csv', 'w', newline='', encoding='utf-8') as f: + writer = csv.writer(f) + writer.writerow(['Лабиринт', 'Стратегия', 'Время(мс)', 'Посещено клеток', 'Длина пути']) + writer.writerows(results) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/victorovaas/lab2/noexit.txt b/victorovaas/lab2/noexit.txt new file mode 100644 index 00000000..0d9e9c53 --- /dev/null +++ b/victorovaas/lab2/noexit.txt @@ -0,0 +1,10 @@ +########## +#S######## +########## +########## +########## +########## +########## +########## +########E# +########## diff --git a/victorovaas/lab2/simple.txt b/victorovaas/lab2/simple.txt new file mode 100644 index 00000000..b7edabb2 --- /dev/null +++ b/victorovaas/lab2/simple.txt @@ -0,0 +1,5 @@ +####### +#S # +# ### # +# E # +#######