【发布时间】:2025-11-27 20:05:04
【问题描述】:
下面的递归函数有助于找到 3X3 矩阵的所有路径,从左上角到右下角,向下或向右移动。但是我想将它更改为一个迭代函数,以便我可以编辑该函数以找到一个特定的完整路径(只有 1 个,从左上角到右下角,通过向右或向下移动)总结(值的总和每个点都等于一个设定的数字)到所需的数字,例如。 12. 这对于更大的矩阵尤其重要,例如。一个 9 X 1000 矩阵。我该怎么做?
达诺兰注意事项:
这些值总是积极的。如果您查看我的 3X3 矩阵 a,您会看到 1s、2s 和 3s 的值。例如,从 1 到 1 到 1 到 2 到 3(目标)是一条完整的路径,总和是 8。
这只会找到所有路径。
a = []
for i in range(3):
r = []
for j in range(3):
r.append(i+1)
a.append(r)
a = 矩阵
1 1 1
2 2 2
3 3 3
all_paths = []
def printall(currentRow, currentColumn, nums):
if (currentRow == len(a) - 1):
for i in range(currentColumn, len(a[0])):
nums.append(a[currentRow][i])
all_paths.append(nums)
return all_paths
if (currentColumn == len(a[0]) - 1):
for i in range(currentRow, len(a)):
nums.append(a[i][currentColumn])
all_paths.append(nums)
return all_paths
nums.append(a[currentRow][currentColumn])
printall(currentRow+1, currentColumn, nums[:])
printall(currentRow, currentColumn+1, nums[:])
printall(0,0,[])
print all_paths
【问题讨论】:
-
你能定义什么是完整路径吗?它是从左上角开始到右下角结束的路径吗?
-
所以你想要一个返回的路径,它的每个点的值的总和等于一个设定的数字?不是路径本身的长度
-
是的,你是对的!
-
很抱歉问题很长,但是值可以是负数还是总是正数?
-
对于 9 x 1000 矩阵,路径数为 1007!/(999!*8!) > 2.5E19。因此,您需要找到一种方法来消除大量路径而不遍历它们。