Python 如何在递归函数中保存最小路径和?
这是我对给定矩阵m x n的解,求最小路径和。它工作正常,但我不知道如何修改它以查看路径/将其保存在某个列表中,如何才能做到这一点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
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]
的移动。
如果你有相等(两个移动都有效)选择你想要的(相等路径)。
一直走到尽头