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

34 lines
1.1 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.strategyObjects.util import restorePath
from task2.mazeObjects.maze import Maze
from task2.mazeObjects.cell import Cell
class DFS(PathFindingStrategy):
"""Поиск в глубину быстрый, но не обязательно кратчайший.
Возвращает None, если пути нет"""
def findPath(self, maze: Maze, start: Cell, exit: Cell):
visited = dict()
parents = dict()
stack = []
stack.append(start)
visited[start] = 0
parents[start] = None
while stack:
current = stack.pop()
# Условие нахождение выхода
if current == exit: break
# Перебор соседей
for hood in maze.getNeighbors(current):
if hood in visited:
continue
visited[hood] = visited[current] + 1
parents[hood] = current
stack.append(hood)
return restorePath(parents, start, exit)