дабавлена стратегия ширины

This commit is contained in:
Proninvv 2026-05-16 20:46:12 +03:00
parent c24592d4e2
commit 550af0164c
5 changed files with 53 additions and 7 deletions

View File

@ -0,0 +1,31 @@
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 []

View File

@ -25,7 +25,7 @@ class Maze:
self.exit = exit
def getCell(self, x, y) -> Cell:
if 0 <= x <= self.width and 0 <= y <= self.height:
if (0 <= x < self.width) and (0 <= y < self.height):
return self.__grid[y][x]
return None

View File

@ -1,5 +1,5 @@
from abc import ABC, abstractmethod
from labirint import Maze, Cell
from Maze import Maze, Cell
class MazeBuilder(ABC):
@ -33,14 +33,11 @@ class TextFileMazeBuilder(MazeBuilder):
elif char == 'E':
cell.isExit = True
self._maze.exit = cell
self._validate()
return self._maze
def validate(self):
def _validate(self):
if self._maze.start is None:
raise "в лабиринте нет старта"
if self._maze.exit is None:
raise "в лабиринте нет начала"
# labir = TextFileMazeBuilder().buildFromFile('text.txt')
# print(labir)

View File

@ -1 +1,7 @@
from MazeBuilder import TextFileMazeBuilder
from BreadthFirstSearch import BFSStrategy
maze1 = TextFileMazeBuilder().buildFromFile("text.txt")
pathh = BFSStrategy.findPath(maze1, maze1.start, maze1.exit)
print(pathh)

View File

@ -0,0 +1,12 @@
from abc import ABC, abstractmethod
from typing import List
from Maze import Maze, Cell
# интерфейс стратегий
class PathFindingStrategy(ABC):
@abstractmethod
def findPath(maze: Maze, start, exit) -> List[Cell]:
""" возвращает список клеток пути (от старта до выхода включительно) или пустой список, если пути нет """
pass