-2

How to update and return count variable to outside of fucntion in python.

for input : [[0,0,0],[0,1,0],[0,0,0]]

std out : 1 1 #as count is incrementing inside function but in each recursion it's changing it's value to 0.

returned output : 0

Expected output : 2

class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
    def f(obstacleGrid,row,col,count):
        if(row==m-1 and col==n-1):
            count+=1
            print(count) #count is incrementing here but not outside the function.
            return
        if(col<n-1 and obstacleGrid[row][col+1]==0):
            f(obstacleGrid,row,col+1,count)
            if(row!=m-1 and col+1!=n-1):
                obstacleGrid[row][col+1]=1
        if(row<m-1 and obstacleGrid[row+1][col]==0):
            f(obstacleGrid,row+1,col,count)
            if(row+1!=m-1 and col!=n-1):
                obstacleGrid[row+1][col]=1
        return
    count = 0 
    m = len(obstacleGrid)
    n = len(obstacleGrid[0])
    f(obstacleGrid,0,0,count)
    return count

Please correct me where I'm wrong. Thanks in Advance.

Jaswanth
  • 1
  • 1

1 Answers1

0

So here count is initialised to 0.

Although there is a modification to count 'count+=1' this is outside the scope of the original function uniquePathsWithObstacles, and local to the function f.

When you modify the value count and return this should be returned with it if you want to keep the values changing. i.e. return count

Peter Mason
  • 101
  • 2