2026-rff_mp/ivantsovma/maze/strategies/dfs_strategy.py

40 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 typing import List
from .path_finding_strategy import PathFindingStrategy
class DFSStrategy(PathFindingStrategy):
"""Поиск в глубину (DFS) - быстрый, но не обязательно кратчайший"""
def __init__(self):
self._visited_count = 0
@property
def name(self) -> str:
return "DFS"
def find_path(self, maze, start, exit_cell) -> List:
"""Находит путь с помощью DFS"""
if not start or not exit_cell:
return []
# Стек для DFS (хранит текущую клетку и путь до неё)
stack = [(start, [start])]
# Множество посещенных клеток
visited = {start}
self._visited_count = 0
while stack:
current, path = stack.pop()
self._visited_count += 1
# Нашли выход
if current == exit_cell:
return path
# Проверяем всех соседей
for neighbor in maze.get_neighbors(current):
if neighbor not in visited:
visited.add(neighbor)
stack.append((neighbor, path + [neighbor]))
# Путь не найден
return []