【问题标题】:How to change this recursive function (return a list of paths for a 3X3 matrix) into iterative function in Python 2.7?如何在 Python 2.7 中将此递归函数(返回 3X3 矩阵的路径列表)更改为迭代函数?
【发布时间】: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。因此,您需要找到一种方法来消除大量路径而不遍历它们。

标签: python recursion


【解决方案1】:

如果有 R 行和 C 列,则必须进行 R-1 下跳和 C-1 右跳。这是不变的。唯一的变化是在顺序 跳跃。如果我们说 dj=R-1 和 rj=C-1,那么路径的总数 是 (dj+rj)!/(dj!rj!)。

因此,我们可以简单地遍历所有独特的排列。注意 itertools.permutations() 将生成 all 排列,而不仅仅是 独特的,所以我们必须过滤掉重复。当然,这 也意味着运行时间将与 (dj+rj)! 成正比,即 非唯一排列。我不会讨论如何有效地生成 独特的排列;例如,请参阅Question 22431637

在下面的代码中,我将行数增加到 4,以帮助 区分行和列。

from itertools import permutations

a = []
for i in range(4):
    r = []
    for j in range(3):
        r.append(i+1)
    a.append(r)

#print a   # Uncomment to trace execution

all_paths = []

def gen_all_paths(matrix):
    rows = len(matrix)
    cols = len(matrix[0])
    dj = rows - 1   # down-jumps
    rj = cols - 1   # right-jumps
    pathmix = 'd' * dj + 'r' * rj

    prev = ()
    for path in permutations(pathmix):
        if path <= prev:   # filter out repeats
            continue
        prev = path

        r, c = 0, 0
        cells = [matrix[0][0]]
        for i in path:
            if i == 'd':
                r += 1
            else:
                c += 1
            cells.append(matrix[r][c])
        #print ''.join(path), cells   # Uncomment to trace execution
        all_paths.append(cells)

gen_all_paths(a)

print all_paths

【讨论】:

  • 我还在纠结这个。那么您将如何编辑此函数以在此 4x4 矩阵中返回所需 sum = 13 的特定路径?
  • 嗯,一种简单的方法是if sum(cells) == 13: return cells