利用队列求解
from collections import deque
dirs = [ lambda x,y:(x+1,y),
lambda x,y:(x-1,y),
lambda x,y:(x,y-1),
lambda x,y:(x,y+1)
]
def print_r(path):
# 创建一个数组存储经过的路径
new_path = []
# 当前节点是path最后一个元素时
curNode = path[-1]
#
while curNode[2] != -1 :
# 把当前节点添加到真正的列表里
new_path.append((curNode[0],curNode[1]))
curNode = path[curNode[2]]
#循环结束 curNode[2] = -1 时 ,为起点,添加至列表
new_path.append((curNode[0],curNode[1]))
# 此时列表的顺序为倒序,需要转换一下
new_path.reverse()
for i in new_path :
print(f'({i[0]},{i[1]})')
def maze_path_queue(n,m,maze):
# 定义队列
queue = deque()
# 初始化 队列
queue.append((0,0,-1))
# 创建一个列表存储出队的元素
path = []
while len(queue) > 0 :
# 标记当前位置
curNode = queue.pop()
# 将出队的元素存至path
path.append(curNode)
# 判断当前位置是否已经在出口
if curNode[0] == n-1 and curNode[1] == m-1:
# print(1)
print_r(path)
return True
# 计算出四个方向的位置
for dir in dirs:
nextNode = dir(curNode[0],curNode[1])
if 0 <= nextNode[0] <= n-1 and 0 <= nextNode[1] <= m-1:
if maze[nextNode[0]][nextNode[1]] == 0 :
queue.append((nextNode[0],nextNode[1],len(path) -1)) # 后续节点进队 ,并记录是哪个节点带来的
maze[nextNode[0]][nextNode[1]] = 2
# print(1)
else :
print('No')
return False
n,m = map(int,input().strip().split())
maze = [list(map(int,input().strip().split())) for _ in range(n)]
maze_path_queue(n,m,maze)



京公网安备 11010502036488号