请修改上述代码,使其能够输出迷宫问题的具体路径
时间: 2023-05-29 13:06:59 浏览: 35
以下是修改后的代码:
class Maze:
def __init__(self, maze):
self.maze = maze
self.rows = len(maze)
self.cols = len(maze[0])
self.start = None
self.end = None
for i in range(self.rows):
for j in range(self.cols):
if maze[i][j] == "S":
self.start = (i, j)
elif maze[i][j] == "E":
self.end = (i, j)
def find_path(self):
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
queue = [self.start]
visited = set()
parent = {}
while queue:
current = queue.pop(0)
if current == self.end:
path = []
while current in parent:
path.append(current)
current = parent[current]
path.append(self.start)
path.reverse()
return path
for direction in directions:
row = current[0] + direction[0]
col = current[1] + direction[1]
if row < 0 or col < 0 or row >= self.rows or col >= self.cols:
continue
if self.maze[row][col] == "#" or (row, col) in visited:
continue
queue.append((row, col))
visited.add((row, col))
parent[(row, col)] = current
return None
maze = [
["#", "#", "#", "#", "#", "#", "#"],
["#", "S", "#", "#", "#", "E", "#"],
["#", " ", " ", " ", " ", " ", "#"],
["#", "#", "#", "#", "#", "#", "#"]
]
m = Maze(maze)
path = m.find_path()
if path:
for p in path:
print(p)
else:
print("No path found.")