📅  最后修改于: 2023-12-03 14:57:58.468000             🧑  作者: Mango
迷宫中的老鼠回溯2是一个经典的回溯算法应用题目。题目要求在一个迷宫中,找到老鼠从起点到终点的路径。迷宫可表示为一个由0和1组成的二维矩阵,其中0代表可通过的路径,1代表墙壁。
def backtrack(row, col):
if (row, col) == (end_row, end_col):
result.append(path.copy())
return
visited[row][col] = True
path.append((row, col))
# 向上
if row > 0 and not visited[row-1][col] and maze[row-1][col] == 0:
backtrack(row-1, col)
# 向下
if row < len(maze)-1 and not visited[row+1][col] and maze[row+1][col] == 0:
backtrack(row+1, col)
# 向左
if col > 0 and not visited[row][col-1] and maze[row][col-1] == 0:
backtrack(row, col-1)
# 向右
if col < len(maze[0])-1 and not visited[row][col+1] and maze[row][col+1] == 0:
backtrack(row, col+1)
visited[row][col] = False
path.pop()
# 迷宫信息
maze = [
[0, 0, 0, 1, 1],
[1, 1, 0, 0, 1],
[1, 1, 0, 1, 1],
[0, 0, 0, 0, 0],
[1, 1, 1, 0, 0]
]
# 起点和终点位置
start_row, start_col = 0, 0
end_row, end_col = 4, 4
# 状态变量
visited = [[False for _ in range(len(maze[0]))] for _ in range(len(maze))]
path = []
result = []
# 调用回溯函数
backtrack(start_row, start_col)
# 打印结果
for p in result:
print(p)
以下是根据给定迷宫和起点、终点位置运行程序得到的示例结果:
[(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (4, 1), (4, 2), (4, 3), (4, 4)]
[(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (4, 1), (4, 2), (3, 2), (3, 3), (4, 3), (4, 4)]
[(0, 0), (1, 0), (2, 0), (3, 0), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (3, 4), (4, 4)]
[(0, 0), (0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 4), (2, 4), (3, 4), (4, 4)]
[(0, 0), (0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 4), (2, 4), (3, 4), (2, 4), (2, 3), (2, 2), (2, 1), (2, 0), (3, 0), (4, 0)]
[(0, 0), (0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 4), (2, 4), (2, 3), (3, 3), (3, 4), (4, 4)]