forked from UNN/2026-rff_mp
54 lines
1.8 KiB
Python
54 lines
1.8 KiB
Python
|
|
from collections import deque
|
|||
|
|
from typing import List, Dict
|
|||
|
|
from .path_finding_strategy import PathFindingStrategy
|
|||
|
|
|
|||
|
|
class BFSStrategy(PathFindingStrategy):
|
|||
|
|
"""Поиск в ширину (BFS) - гарантирует кратчайший путь"""
|
|||
|
|
|
|||
|
|
def __init__(self):
|
|||
|
|
self._visited_count = 0
|
|||
|
|
|
|||
|
|
@property
|
|||
|
|
def name(self) -> str:
|
|||
|
|
return "BFS"
|
|||
|
|
|
|||
|
|
def find_path(self, maze, start, exit_cell) -> List:
|
|||
|
|
"""Находит путь с помощью BFS"""
|
|||
|
|
if not start or not exit_cell:
|
|||
|
|
return []
|
|||
|
|
|
|||
|
|
# Очередь для BFS
|
|||
|
|
queue = deque([start])
|
|||
|
|
# Множество посещенных клеток
|
|||
|
|
visited = {start}
|
|||
|
|
# Словарь для восстановления пути
|
|||
|
|
parent = {start: None}
|
|||
|
|
self._visited_count = 0
|
|||
|
|
|
|||
|
|
while queue:
|
|||
|
|
current = queue.popleft()
|
|||
|
|
self._visited_count += 1
|
|||
|
|
|
|||
|
|
# Нашли выход
|
|||
|
|
if current == exit_cell:
|
|||
|
|
return self._reconstruct_path(parent, exit_cell)
|
|||
|
|
|
|||
|
|
# Проверяем всех соседей
|
|||
|
|
for neighbor in maze.get_neighbors(current):
|
|||
|
|
if neighbor not in visited:
|
|||
|
|
visited.add(neighbor)
|
|||
|
|
parent[neighbor] = current
|
|||
|
|
queue.append(neighbor)
|
|||
|
|
|
|||
|
|
# Путь не найден
|
|||
|
|
return []
|
|||
|
|
|
|||
|
|
def _reconstruct_path(self, parent: Dict, end) -> List:
|
|||
|
|
"""Восстанавливает путь от终点 до старта"""
|
|||
|
|
path = []
|
|||
|
|
current = end
|
|||
|
|
while current is not None:
|
|||
|
|
path.append(current)
|
|||
|
|
current = parent.get(current)
|
|||
|
|
return list(reversed(path))
|