2026-rff_mp/MusinAA/task2/strategyObjects/BFS.py

42 lines
1.3 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.

from task2.strategyObjects.pathFindingStrategy import PathFindingStrategy
from task2.mazeObjects.maze import Maze
from task2.mazeObjects.cell import Cell
import queue
class BFS(PathFindingStrategy):
"""Поиск в ширину гарантирует кратчайший путь по количеству шагов."""
def findPath(self, maze: Maze, start: Cell, exit: Cell):
visited = dict()
parents = dict()
q = queue.Queue()
q.put(start)
visited[start] = 0
parents[start] = None
while not q.empty():
current = q.get()
# Условие нахождение выхода
if current == exit: break
# Перебор соседей
for hood in maze.getNeighbors(current):
if hood in visited:
continue
visited[hood] = visited[current] + 1
parents[hood] = current
q.put(hood)
return self.restorePath(parents, start, exit)
def restorePath(self, parents: dict, start: Cell, exit: Cell) -> list[Cell]|None:
path = []
current = exit
while current:
path.append(current)
if current not in parents:
return []
current = parents[current]
return path[::-1]