题解 | #迷宫问题#
迷宫问题
https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
import sys
def walk(path, x, y):
if (y + 1 < col) and (MAP[x][y + 1] == 0) and ((x, y + 1) not in path):
walk(path + [(x, y + 1)], x, y + 1)
if y - 1 >= 0 and (MAP[x][y - 1] == 0) and ((x, y - 1) not in path):
walk(path + [(x, y - 1)], x, y - 1)
if x + 1 < row and MAP[x + 1][y] == 0 and ((x + 1, y) not in path):
walk(path + [(x + 1, y)], x + 1, y)
if x - 1 >= 0 and (MAP[x - 1][y] == 0) and ((x - 1, y) not in path):
walk(path + [(x - 1, y)], x - 1, y)
if (x, y) == (row - 1, col - 1):
for p in path:
print(f"({p[0]},{p[1]})")
while True:
try:
row, col = list(map(int, input().split()))
MAP = [[i for i in map(int, input().split())] for _ in range(row)]
path = [(0, 0)]
walk(path,0,0)
except:
break
单路径迷宫问题,回溯方式是按照下一步是否是1不可行,可行就回溯函数,并且注意不能再已走的path中
# print(MAP[0][1])