问题描述
我需要在 m x n
的 0 和 1 的迷宫中找到最短路径(其中 1 是一堵墙,0 是一个空白空间)从 [0][0]
到 [m-1][n-1]
以及允许的移动是 U、D、L 和 R。路径是指要覆盖的单元格数量,包括源和目标。
出于某些目的,我需要递归地进行。我编写了一个函数来查找所有可能的路径及其长度。以一种粗暴的方式,它只是环顾四周(U、D、L、R),如果尚未访问过该单元格并且它不是墙,则它会递归访问它。
def find_path(maze,i = 0,j = 0,path = 1):
m = len(maze)
n = len(maze[0])
if i == m - 1 and j == n - 1:
print("Path to destination [m - 1][n - 1]: {0}".format(path))
maze[i][j] = 1
if 0 <= i < m and 0 <= j - 1 < n and maze[i][j - 1] == 0:
find_path(maze,i,j - 1,path + 1)
if 0 <= i < m and 0 <= j + 1 < n and maze[i][j + 1] == 0:
find_path(maze,j + 1,path + 1)
if 0 <= i - 1 < m and 0 <= j < n and maze[i - 1][j] == 0:
find_path(maze,i - 1,j,path + 1)
if 0 <= i + 1 < m and 0 <= j < n and maze[i + 1][j] == 0:
find_path(maze,i + 1,path + 1)
maze[i][j] = 0
return path
我的问题:
-
我不明白如何保存最短路径并在到达目的地时将其传递给所有函数调用。函数中的某处应该是一行类似于 if
path < shortest_path: shortest_path = path
; -
我不明白如何从函数返回最短路径。我应该返回一个元组
(path,shortest_path)
还是什么?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)