2026-rff_mp/ProninVV/task-2-oop/BreadthFirstSearch.py

32 lines
994 B
Python

from strategy import PathFindingStrategy
from Maze import Maze, Cell
class BFSStrategy(PathFindingStrategy):
def findPath(maze: Maze, start: Cell, exit: Cell):
if not start or not exit:
return []
# очерель: перывй вошел - первый вышел
queue = [start]
# будем хранить откуда в какую клетку пришли
parents = {start: None}
while (len(queue) != 0):
u = queue.pop(0)
if u == exit:
path = []
current = exit
while current is not None:
path.append(current)
current = parents[current]
path.reverse()
return path
childs = maze.getNeighbors(u)
for child in childs:
if child not in parents:
parents[child] = u
queue.append(child)
return []