def solve_maze(maze, start, end):
m, n = len(maze), len(maze[0])
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] # 上下左右四个方向
stack = [] # 使用列表模拟栈
visited = [[False] * n for _ in range(m)] # 记录已经访问过的位置
stack.append(start)
visited[start[0]][start[1]] = True
while stack:
curr = stack[-1]
if curr == end:
return stack
x, y = curr
for dx, dy in directions:
nx, ny = x + dx, y + dy
if 0 <= nx < m and 0 <= ny < n and maze[nx][ny] == 0 and not visited[nx][ny]:
stack.append((nx, ny))
visited[nx][ny] = True
break
else:
stack.pop()
return []
maze = [
[1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 1, 0, 0, 1],
[1, 1, 0, 0, 0, 1, 1],
[1, 1, 1, 1, 0, 1, 1],
[1, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1]
]
start = (1, 1)
end = (4, 5)
path = solve_maze(maze, start, end)
if path:
print("找到路径:")
for position in path:
print(position)
else:
print("无法找到路径!")