Can any one help me fix my python program?

  • 0

    Here's my code:

    def uniquePathsWithObstacles(self, obstacleGrid):
        if not obstacleGrid: return 0
        m,n = len(obstacleGrid),len(obstacleGrid[0])
        mat = [[0]*(n+1)]*(m+1)
        mat[m-1][n] = 1
        for i in reversed(range(m)):
            for j in reversed(range(n)):
                mat[i][j] = 0 if obstacleGrid[i][j] == 1 else mat[i][j+1]+mat[i+1][j]
        return mat[0][0]

    When input is [[0],[0]] the output is 2, which should be 1 as correct answer.

    I can't find out why and how to fix it. Thanks if anyone can help me fix this problem!

  • 1

    Try initialize the matrix using

    [[0 for col in range(n+1)] for row in range(m+1)]

    instead of


    which makes m+1 copies of the reference of the same 1D array.

  • 0

    Thank you, that works! But could you explain what's the difference between these two?
    Because I tried:

    lis1 = [[0 for col in range(n+1)] for row in range(m+1)]
    lis2 = [[0]*(n+1)]*(m+1)
    print lis1 == lis2

    the result is True, so I don't see any difference between them.

  • 0

    try lis2[0][0] = 5, then print lis2, u will know the difference

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.