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

47 lines
1.3 KiB
Python

#!/usr/bin/env python
# coding: utf-8
# In[ ]:
from typing import List, Dict, Optional
from strategiesPathfinding_strategy import PathFindingStrategy
from modelsMaze import Maze
from modelsCell import Cell
class DFSStrategy(PathFindingStrategy):
"""Поиск в глубину - быстрый, но не обязательно кратчайший."""
@property
def name(self) -> str:
return "DFS"
def find_path(self, maze: Maze, start: Cell, exit_cell: Cell) -> List[Cell]:
if start == exit_cell:
return [start]
stack = [start]
came_from: Dict[Cell, Optional[Cell]] = {start: None}
visited_count = 0
while stack:
current = stack.pop()
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
stack.append(neighbor)
self._last_visited_count = visited_count
return []
@property
def last_visited_count(self) -> int:
return getattr(self, '_last_visited_count', 0)