n * n矩阵中所有可能的路径 - python

时间:2015-09-14 00:51:38

标签: python recursion matrix

我正在尝试解决面试问题:

  

给定n * n矩阵,假设您从左上角的单元格开始(即0,0)。您可以向右或向下移动,您必须前往右下方的单元格。获取小于给定值的最大值。例如,假设3 * 3矩阵,给定值为5

0 1 2
2 1 2
3 2 1

optimal path is 0 -> 1 -> 1 -> 2 -> 1 = 5

我开始使用递归编码但答案不正确。有什么建议吗?

def findAllPaths(currX, currY, path, grid, sum):
    #print currX, currY
    if currX == len(grid)-1:
        i = currY
        temp = 0
        while i < len(grid):
            path = path + str(grid[currX][i])
            temp += grid[currX][i]
            i += 1
        sum.append(temp)
        #print 'first loop', sum, path
        return
    if currY == len(grid)-1:
        i = currX
        temp = 0
        while i < len(grid):
            path = path + str(grid[i][currY])
            temp += grid[i][currY]
            i += 1
        sum.append(temp)
        #print 'second loop', sum, path
        return
    #print currX, currY
    #path = path + str(grid[currX][currY])
    findAllPaths(currX+1,currY,path,grid, sum)
    findAllPaths(currX, currY+1,path,grid, sum)

    return sum

2 个答案:

答案 0 :(得分:0)

你没有删除东西而附加了sum和path。这是递归函数的问题,因为您将尝试一个路径,当您回溯时,您不会删除它们。您需要复制(cpysum = sum[:])或在递归后删除内容但找不到解决方案。

答案 1 :(得分:0)

我正在使用动态编程来完成任务。通过查找路径的最小值,程序只需要计算当前值+最后一步的最小值。

def minPathSum(grid):
        res = 0
        if grid:
            n,m = len(grid),len(grid[0])
            dp = [[0]* m for _ in range(n)]
            dp[0][0]= grid[0][0]
            for i in range(1,m):
                dp[0][i] = dp[0][i-1] + grid[0][i]
            for i in range(1,n):
                dp[i][0] = dp[i-1][0]+grid[i][0]

            for i in range(1,n):
                for j in range(1,m):
                    dp[i][j] = grid[i][j]
                    dp[i][j] += min(dp[i][j-1],dp[i-1][j])

            res = dp[-1][-1]
        return res

grid = [ [0,1,2],[2 ,1 ,2],[3 ,2 ,1]]
print(minPathSum(grid))