matrix = []
row = 0
col = 0
finestpath = []
tmppath = []
def getinput():
global row
global col
row, col = [int(x) for x in input().strip().split()]
for i in range(0, row):
line = [int(x) for x in input().strip().split()]
matrix.append(line)
if matrix[row - 1][col - 1] != 0:
return False
def findpath(x, y):
# 先判断坐标是否合法
if x >= col or x < 0 or y >= row or y < 0:
return
# 在判断坐标节点的值
if matrix[x][y] == 1:
return
# 当前节点可用
tmppath.append((x, y))
# 当前节点是不是已经是出口
if x == col - 1 and y == row - 1:
if not finestpath:
finestpath[:] = tmppath[:]
else:
if len(finestpath) > len(tmppath):
finestpath[:] = tmppath[:]
# 在找下一个通路节点之前先把自己锁死
matrix[x][y] = 1
# 上下左右找通路
findpath(x, y - 1)
findpath(x - 1, y)
findpath(x, y + 1)
findpath(x + 1, y)
# 从x,y开始,并经历过上左下右的递归搜索后,没有找到出口,则还原当前节点状态,并把自己从tmppath中移除,因为
# 当前节点不是通路的一份子
matrix[x][y] = 0
tmppath.pop()
getinput()
findpath(0, 0)
# print(finestpath)
for ele in finestpath:
print('('+str(ele[0])+','+str(ele[1])+')')
[DnA] 迷宫问题
最新推荐文章于 2024-03-01 12:13:15 发布