2026-rff_mp/nikolaevda/task2/Zadanie2.py
2026-05-23 19:48:29 +03:00

282 lines
8.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import sys
from collections import deque
import heapq
import time
import os
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):
return f"Cell({self.x}, {self.y})"
class Maze:
"""лабиринт"""
def __init__(self, width, height):
self.width = width
self.height = height
self.cells = [[Cell(x, y) for x in range(width)] for y in range(height)]
self.start = None
self.exit = None
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 = []
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
for dx, dy in directions:
neighbor = self.get_cell(cell.x + dx, cell.y + dy)
if neighbor and neighbor.is_passable():
neighbors.append(neighbor)
return neighbors
def set_start(self, x, y):
cell = self.get_cell(x, y)
if cell:
cell.is_start = True
self.start = cell
def set_exit(self, x, y):
cell = self.get_cell(x, y)
if cell:
cell.is_exit = True
self.exit = cell
class MazeBuilder:
"""интерфейс строителя лабиринта"""
def buildFromFile(self, filename):
raise NotImplementedError
class TextFileMazeBuilder(MazeBuilder):
"""загрузка лабиринта из текстового файла"""
def buildFromFile(self, filename):
with open(filename, 'r', encoding='utf-8') as f:
lines = [line.rstrip('\n') for line in f.readlines()]
height = len(lines)
width = max(len(line) for line in lines) if height > 0 else 0
for i in range(height):
if len(lines[i]) < width:
lines[i] = lines[i] + ' ' * (width - len(lines[i]))
maze = Maze(width, height)
start_count = 0
exit_count = 0
for y, line in enumerate(lines):
for x, ch in enumerate(line):
if ch == '#':
maze.get_cell(x, y).is_wall = True
elif ch == 'S':
maze.set_start(x, y)
start_count += 1
elif ch == 'E':
maze.set_exit(x, y)
exit_count += 1
else:
maze.get_cell(x, y).is_wall = False
if start_count != 1 or exit_count != 1:
raise ValueError(f"Ошибка: S={start_count}, E={exit_count} (нужно по одному)")
return maze
class SearchStats:
"""статистика поиска"""
def __init__(self, time_ms=0, visited_cells=0, path_length=0):
self.time_ms = time_ms
self.visited_cells = visited_cells
self.path_length = path_length
def __str__(self):
return f"Время: {self.time_ms:.2f} мс, Посещено: {self.visited_cells}, Длина пути: {self.path_length}"
class PathFindingStrategy:
"""интерфейс стратегии поиска пути"""
def findPath(self, maze, start, exit):
raise NotImplementedError
def get_name(self):
raise NotImplementedError
class BFSStrategy(PathFindingStrategy):
"""BFS - гарантирует кратчайший путь"""
def get_name(self):
return "BFS (Поиск в ширину)"
def findPath(self, maze, start, exit):
from collections import deque
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):
"""DFS - быстрый, но не обязательно кратчайший"""
def get_name(self):
return "DFS (Поиск в глубину)"
def findPath(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):
"""алгоритм A Star - оптимальный и быстрый с эвристикой"""
def get_name(self):
return "A Star"
def _heuristic(self, a, b):
return abs(a.x - b.x) + abs(a.y - b.y)
def findPath(self, maze, start, exit):
if not start or not exit:
return [], 0
import heapq
heap = []
counter = 0
start_f = self._heuristic(start, exit)
heapq.heappush(heap, (start_f, counter, start))
came_from = {}
g_score = {start: 0}
f_score = {start: start_f}
visited = set()
visited.add(start)
while heap:
current_f, _, current = heapq.heappop(heap)
if current == exit:
path = []
while current in came_from:
path.append(current)
current = came_from[current]
path.append(start)
path.reverse()
return path, len(visited)
if current_f > f_score.get(current, float('inf')):
continue
for neighbor in maze.get_neighbors(current):
tentative_g = g_score[current] + 1
if tentative_g < g_score.get(neighbor, float('inf')):
came_from[neighbor] = current
g_score[neighbor] = tentative_g
new_f = tentative_g + self._heuristic(neighbor, exit)
f_score[neighbor] = new_f
counter += 1
heapq.heappush(heap, (new_f, counter, neighbor))
visited.add(neighbor)
return [], len(visited)
class DijkstraStrategy(PathFindingStrategy):
"""алгоритм Дейкстры"""
def get_name(self):
return "Дейкстра (Dijkstra)"
def findPath(self, maze, start, exit):
if not start or not exit:
return [], 0
import heapq
heap = []
counter = 0
heapq.heappush(heap, (0, counter, start))
distances = {start: 0}
came_from = {}
visited = set()
visited.add(start)
while heap:
current_dist, _, current = heapq.heappop(heap)
if current == exit:
path = []
while current in came_from:
path.append(current)
current = came_from[current]
path.append(start)
path.reverse()
return path, len(visited)
if current_dist > distances.get(current, float('inf')):
continue
for neighbor in maze.get_neighbors(current):
new_dist = current_dist + 1
if new_dist < distances.get(neighbor, float('inf')):
distances[neighbor] = new_dist
came_from[neighbor] = current
counter += 1
heapq.heappush(heap, (new_dist, counter, neighbor))
visited.add(neighbor)
return [], len(visited)