题解 | #迷宫问题# 第一次自己写出来的递归,记录一下。
迷宫问题
https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
m, n = map(int, input().split())
maze = [[0]*n for _ in range(m)]
route = [[0, 0]]
for i in range(m):
maze[i] = list(map(int, input().split()))
def maze_loop():
location = route[len(route) - 1]
mark = False
# 没到终点
if location != [len(maze) - 1, len(maze[0]) - 1]:
# 往右走
if location[1] != len(maze[0]) - 1 and maze[location[0]][location[1] + 1] == 0 and [location[0], location[1] + 1] not in route:
route.append([location[0], location[1] + 1])
mark = maze_loop()
if not mark:
route.pop()
else:
return True
# 往下走
if location[0] != len(maze) - 1 and maze[location[0] + 1][location[1]] == 0 and [location[0] + 1, location[1]] not in route:
route.append([location[0] + 1, location[1]])
mark = maze_loop()
if not mark:
route.pop()
else:
return True
# 往左走
if location[1] != 0 and maze[location[0]][location[1] - 1] == 0 and [location[0], location[1] - 1] not in route:
route.append([location[0], location[1] - 1])
mark = maze_loop()
if not mark:
route.pop()
else:
return True
# 往上走
if location[0] != 0 and maze[location[0] - 1][location[1]] == 0 and [location[0] - 1, location[1]] not in route:
route.append([location[0] - 1, location[1]])
mark = maze_loop()
if not mark:
route.pop()
else:
return True
# 到终点了
else:
for l in route:
print('(' + str(l[0]) + ',' + str(l[1]) + ')')
return True
maze_loop()
第一次自己写出来递归,记录一下!哎,感觉自己有些进步了。感谢牛客,感谢评论区大佬。代码水平和规范度还有待提高,继续加油!
查看2道真题和解析