【发布时间】:2020-05-28 10:35:19
【问题描述】:
例如给定以下矩阵:
[[[0, 8], [0, 3], [0, 8]],
[[8, 0], [3, 0], [0, 5]],
[[0, 1], [0, 6], [0, 0]]]
每个元组的第一个数字是食物,第二个数字是水。我需要从右下角到左上角,我只能向上或向左移动。
我需要收集尽可能多的食物和水,这样我才能尽可能地活下去。对于我想要生存的每一天,我需要 1 份食物和 1 份水,所以如果我可以在导致 (7,4) 的路径和会导致 (6,6) 的路径之间进行选择,正确的选择是 (6,6 ) 因为这样我可以活 6 天。
如何通过所述矩阵找到最佳路径?
我当前的代码在下面,但是它不起作用(它找到了一个非常高成本的路径,但不是最高的),我不知道如何去做。尽管有人告诉我要避免递归,但我不知道如何开始实现它。
def maxSuppliesPath(matrix):
n = len(matrix) - 1
bestPath = matrix
# Initialize first column of bestPath array
for i in range(1, n + 1):
if bestPath[i][0] == 0:
bestPath[i][0] = bestPath[i - 1][0]
else:
bestPath[i][0] = (bestPath[i][0][0] + bestPath[i - 1][0][0], bestPath[i][0][1] + bestPath[i - 1][0][1])
# Initialize first row of bestPath array
for j in range(1, n + 1):
if bestPath[0][j] == 0:
bestPath[0][j] = bestPath[0][j - 1]
else:
bestPath[0][j] = (bestPath[0][j - 1][0] + bestPath[0][j][0], bestPath[0][j - 1][1] + bestPath[0][j][1])
# Construct rest of the bestPath array
for i in range(1, n + 1):
for j in range(1, n + 1):
if min(bestPath[i][j - 1][0] + bestPath[i][j][0], bestPath[i][j - 1][1] + bestPath[i][j][1]) > min(
bestPath[i - 1][j][0] + bestPath[i][j][0], bestPath[i - 1][j][1] + bestPath[i][j][1]):
bestPath[i][j] = (bestPath[i][j - 1][0] + bestPath[i][j][0], bestPath[i][j - 1][1] + bestPath[i][j][1])
else:
bestPath[i][j] = (bestPath[i - 1][j][0] + bestPath[i][j][0], bestPath[i - 1][j][1] + bestPath[i][j][1])
return min(bestPath[n][n][0], bestPath[n][n][1])
【问题讨论】:
-
我已经为你改了,虽然我不明白为什么方向会改变答案?
-
好的,谢谢,我一直在互联网上搜索任何讨论像我这样的问题的东西,但到目前为止我没有运气,尽管有大量关于路径查找的帖子只涉及一个值。
-
我添加了一些解释性文字。如果您有任何问题,请告诉我。
标签: python matrix optimization path-finding