【问题标题】:recording the steps taken of minimum sum path in a matrix记录矩阵中最小和路径所采取的步骤
【发布时间】:2021-10-19 23:39:27
【问题描述】:

假设我有一个矩阵 [[1, -2, 3], [1, 2, 4], [2, 1, 6]],我必须找到从左上角开始的总和最小的路径到右下角。

我使用了下面的 dp 方法(通过制作另一个表格并将经过的单元格相加):

new_tr[0][0] = mat_tr[0][0]
for j in range(1, N):
    new_tr[0][j] = mat_tr[0][j] + new_tr[0][j - 1]
for i in range(1, M):
    new_tr[i][0] = mat_tr[i][0] + new_tr[i - 1][0]
for i in range(1, M):
    for j in range(1, N):
        new_tr[i][j] = min(new_tr[i - 1][j], new_tr[i][j - 1]) + mat_tr[i][j]
        print(new_tr[i][j])

我想记录为获得最小总和而采取的每一步。 (例如(右、下、下、右)在 [[1, -2, 3], [1, 2, 4], [2, 1, 6]] 的情况下)

我有什么方法可以这样做?

【问题讨论】:

  • 您写了“从右上角到左下角的旅行”,但所需的输出似乎是您假设从左上角到右下角旅行。对吗?
  • 是的,这是正确的。抱歉打错了!

标签: python matrix dynamic-programming


【解决方案1】:

尝试以下递归方法:

mat = [[1, -2, 3], [1, 2, 4], [2, 1, 6]]

def smallest(mat, x=0, y=0):
    # mat: nested list for the matrix
    # x, y: current position
    # output: tuple (val, path)
    #         val: smallest value from the current position to the destination
    #         path: list. path to the destination
    rows, cols = len(mat), len(mat[0]) # size of the matrix
    if (x, y) == (rows - 1, cols - 1): # if arrived at the southeast corner
        return mat[x][y], []
    candidates = [] # store results from deeper calls
    if x < rows - 1: # if we can go down
        candidates.append([*smallest(mat, x + 1, y), 'down'])
    if y < cols - 1: # if we can go right
        candidates.append([*smallest(mat, x, y + 1), 'right'])
    candidate = min(candidates, key=lambda u: u[0]) # pick the smaller result
    return mat[x][y] + candidate[0], [candidate[2], *candidate[1]]

print(smallest(mat)) # (8, ['right', 'down', 'down', 'right'])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2019-11-29
    • 1970-01-01
    相关资源
    最近更新 更多