2026-rff_mp/MininaVD/docs2/data2/strategiesBfs_strategy.py

49 lines
1.4 KiB
Python

#!/usr/bin/env python
# coding: utf-8
# In[ ]:
from collections import deque
from typing import List, Dict, Optional
from strategiesPathfinding_strategy import PathFindingStrategy
from modelsMaze import Maze
from modelsCell import Cell
class BFSStrategy(PathFindingStrategy):
"""Поиск в ширину - гарантирует кратчайший путь."""
@property
def name(self) -> str:
return "BFS"
def find_path(self, maze: Maze, start: Cell, exit_cell: Cell) -> List[Cell]:
if start == exit_cell:
return [start]
queue = deque([start])
came_from: Dict[Cell, Optional[Cell]] = {start: None}
visited_count = 0 # Для статистики
while queue:
current = queue.popleft()
visited_count += 1
if current == exit_cell:
# Сохраняем количество посещённых клеток для статистики
self._last_visited_count = visited_count
return self._reconstruct_path(came_from, start, current)
for neighbor in maze.get_neighbors(current):
if neighbor not in came_from:
came_from[neighbor] = current
queue.append(neighbor)
self._last_visited_count = visited_count
return []
@property
def last_visited_count(self) -> int:
return getattr(self, '_last_visited_count', 0)