[2] добавил поиск в глубину
This commit is contained in:
parent
308ee2d716
commit
a339b8fb6f
|
|
@ -40,6 +40,33 @@ class BfsStrategy:
|
||||||
"visited": visited_count,
|
"visited": visited_count,
|
||||||
"length": len(path)
|
"length": len(path)
|
||||||
}
|
}
|
||||||
|
class DfsStrategy:
|
||||||
|
def solve(self, maze):
|
||||||
|
start = maze.start
|
||||||
|
finish = maze.finish
|
||||||
|
stack = [start]
|
||||||
|
previous = {start: None}
|
||||||
|
visited_count = 0
|
||||||
|
|
||||||
|
while stack:
|
||||||
|
current = stack.pop()
|
||||||
|
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
|
||||||
|
stack.append(next_cell)
|
||||||
|
|
||||||
|
path = build_path(previous, start, finish)
|
||||||
|
return {
|
||||||
|
"name": "DFS",
|
||||||
|
"path": path,
|
||||||
|
"visited": visited_count,
|
||||||
|
"length": len(path)
|
||||||
|
}
|
||||||
|
|
||||||
class MazeSolver:
|
class MazeSolver:
|
||||||
def __init__(self, strategy):
|
def __init__(self, strategy):
|
||||||
|
|
@ -50,7 +77,7 @@ class MazeSolver:
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
maze = MazeBuilder().from_file("raskatovia/docs/data/task2/maps/simple.txt").build()
|
maze = MazeBuilder().from_file("raskatovia/docs/data/task2/maps/simple.txt").build()
|
||||||
solver = MazeSolver(BfsStrategy())
|
solver = MazeSolver(DfsStrategy())
|
||||||
result = solver.solve(maze)
|
result = solver.solve(maze)
|
||||||
print("algorithm:", result["name"])
|
print("algorithm:", result["name"])
|
||||||
print("visited:", result["visited"])
|
print("visited:", result["visited"])
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue
Block a user