forked from UNN/2026-rff_mp
[2] добавил поиск в ширину
This commit is contained in:
parent
a912487cdc
commit
308ee2d716
|
|
@ -0,0 +1,58 @@
|
|||
from collections import deque
|
||||
from maze import MazeBuilder
|
||||
|
||||
def build_path(previous, start, finish):
|
||||
if finish not in previous:
|
||||
return []
|
||||
path = []
|
||||
current = finish
|
||||
while current != start:
|
||||
path.append(current)
|
||||
current = previous[current]
|
||||
path.append(start)
|
||||
path.reverse()
|
||||
return path
|
||||
|
||||
class BfsStrategy:
|
||||
def solve(self, maze):
|
||||
start = maze.start
|
||||
finish = maze.finish
|
||||
queue = deque([start])
|
||||
previous = {start: None}
|
||||
visited_count = 0
|
||||
|
||||
while queue:
|
||||
current = queue.popleft()
|
||||
visited_count += 1
|
||||
|
||||
if current == finish:
|
||||
break
|
||||
|
||||
for next_cell in maze.neighbors(current[0], current[1]):
|
||||
if next_cell not in previous:
|
||||
previous[next_cell] = current
|
||||
queue.append(next_cell)
|
||||
|
||||
path = build_path(previous, start, finish)
|
||||
return {
|
||||
"name": "BFS",
|
||||
"path": path,
|
||||
"visited": visited_count,
|
||||
"length": len(path)
|
||||
}
|
||||
|
||||
class MazeSolver:
|
||||
def __init__(self, strategy):
|
||||
self.strategy = strategy
|
||||
|
||||
def solve(self, maze):
|
||||
return self.strategy.solve(maze)
|
||||
|
||||
if __name__ == "__main__":
|
||||
maze = MazeBuilder().from_file("raskatovia/docs/data/task2/maps/simple.txt").build()
|
||||
solver = MazeSolver(BfsStrategy())
|
||||
result = solver.solve(maze)
|
||||
print("algorithm:", result["name"])
|
||||
print("visited:", result["visited"])
|
||||
print("length:", result["length"])
|
||||
print(maze.draw(result["path"]))
|
||||
Loading…
Reference in New Issue
Block a user