2026-rff_mp/MininaVD/docs2/data2/strategiesBfs_strategy.ipynb
2026-05-20 21:02:01 +03:00

76 lines
2.4 KiB
Plaintext

{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "263fab53-6f76-4853-b167-a51b1198ddee",
"metadata": {},
"outputs": [],
"source": [
"from collections import deque\n",
"from typing import List, Dict, Optional\n",
"from strategiesPathfinding_strategy import PathFindingStrategy\n",
"from modelsMaze import Maze\n",
"from modelsCell import Cell\n",
"\n",
"class BFSStrategy(PathFindingStrategy):\n",
" \"\"\"Поиск в ширину - гарантирует кратчайший путь.\"\"\"\n",
" \n",
" @property\n",
" def name(self) -> str:\n",
" return \"BFS\"\n",
" \n",
" def find_path(self, maze: Maze, start: Cell, exit_cell: Cell) -> List[Cell]:\n",
" if start == exit_cell:\n",
" return [start]\n",
" \n",
" queue = deque([start])\n",
" came_from: Dict[Cell, Optional[Cell]] = {start: None}\n",
" visited_count = 0 # Для статистики\n",
" \n",
" while queue:\n",
" current = queue.popleft()\n",
" visited_count += 1\n",
" \n",
" if current == exit_cell:\n",
" # Сохраняем количество посещённых клеток для статистики\n",
" self._last_visited_count = visited_count\n",
" return self._reconstruct_path(came_from, start, current)\n",
" \n",
" for neighbor in maze.get_neighbors(current):\n",
" if neighbor not in came_from:\n",
" came_from[neighbor] = current\n",
" queue.append(neighbor)\n",
" \n",
" self._last_visited_count = visited_count\n",
" return []\n",
" \n",
" @property\n",
" def last_visited_count(self) -> int:\n",
" return getattr(self, '_last_visited_count', 0)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python [conda env:base] *",
"language": "python",
"name": "conda-base-py"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.13.9"
}
},
"nbformat": 4,
"nbformat_minor": 5
}