def minCostPath(grid):
dp = [[0 for i in range(len(grid))] for j in range(len(grid[0]))]
dp[0][0] = grid[0][0]
back = {}
path = []
for i in range(1, len(grid)):
dp[0][i] = dp[0][i - 1] + grid[0][i]
for i in range(1, len(grid[0])):
dp[i][0] = dp[i - 1][0] + grid[i][0]
if dp[1][0] < dp[0][1]:
back[(1, 0)] = (0, 0)
else:
back[(0, 1)] = (0, 0)
for i in range(1, len(grid)):
for j in range(1, len(grid[0])):
dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1])
if dp[i - 1][j] < dp[i][j - 1]:
back[(i, j)] = (i - 1, j)
else:
back[(i, j)] = (i, j - 1)
curr = (len(grid) - 1, len(grid[0]) - 1)
while curr != (0, 0):
path.append(curr)
curr = back[curr]
return dp[len(grid) - 1][len(grid[0]) - 1], reversed(path)
我创建了一个DP解决方案,以查找从网格左上方到网格右下方的最小成本路径。然后,我尝试将所选单元格的前一个单元格存储到字典中,并使用它来计算最后的路径。
但是,我一直在获得
{(0, 1): (0, 0), (1, 1): (0, 1), (1, 2): (1, 1), (2, 1): (2, 0), (2, 2): (2, 1)}
其中grid = [[1, 7, 9], [8, 6, 3], [1, 6, 7]]
对于我的结果,这看起来很奇怪,并且缺少一些单元格。
我的逻辑有什么问题以及如何解决?
我解决的问题是:
Given a 2D-matrix where each cell has a cost to travel. You have to write an algorithm to find a path from left-top corner to bottom-right corner with minimum travel cost. You can move only right or down.
我有钱,但是我没有找到确切的解决方法。