Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在递归函数中保存最小路径和?_Python_Algorithm - Fatal编程技术网

Python 如何在递归函数中保存最小路径和?

Python 如何在递归函数中保存最小路径和?,python,algorithm,Python,Algorithm,这是我对给定矩阵m x n的解,求最小路径和。它工作正常,但我不知道如何修改它以查看路径/将其保存在某个列表中,如何才能做到这一点 def get_path(matrix, x, y, seen): if (x, y) in seen: return seen[x, y] x_end = len(matrix) - 1 y_end = len(matrix[0]) - 1 current = matrix[x][y] if x == x_e

这是我对给定矩阵m x n的解,求最小路径和。它工作正常,但我不知道如何修改它以查看路径/将其保存在某个列表中,如何才能做到这一点

def get_path(matrix, x, y, seen):
    if (x, y) in seen:
        return seen[x, y]
    x_end = len(matrix) - 1
    y_end = len(matrix[0]) - 1
    current = matrix[x][y]
    if x == x_end and y == y_end:
        return current
    possible_moves = []
    if x < len(matrix) - 1:
        possible_moves.append([x + 1, y])
    if y < len(matrix[0]) - 1:
        possible_moves.append([x, y + 1])
    results = [
        current + get_path(matrix, *possible, seen) for possible in possible_moves
    ]
    current_best = min(results)
    seen[x, y] = current_best
    return current_best
def get_路径(矩阵,x,y,可见):
如果(x,y)处于可见状态:
返回所见[x,y]
x_end=len(矩阵)-1
y_end=len(矩阵[0])-1
电流=矩阵[x][y]
如果x==x_端且y==y_端:
回流
可能的_移动=[]
如果x
您不需要这样做

get_path
返回后,从0,0开始查找
seed[x',y']=seed[x,y]-矩阵[x,y]
的移动。 如果你有相等(两个移动都有效)选择你想要的(相等路径)。 一直走到尽头