1

This is my code, I am confused why that I got the exception local variable "final" referenced before assignment. I have tried to declare it as global in dfs function but still no help. I am wondering why that vistited is correctly referenced by dfs function while final is not.

def movingCount(self, m, n, k):
        def calculate(x, y):
            x_str = str(x)
            y_str = str(y)
            result = 0
            for i in x_str:
                result += int(i)
            for j in y_str:
                result += int(j)
            return result
        vistited = [[0]*n for _ in range(m)]
        final = 0
        def dfs(x, y):
            print(vistited, final)
            if x == m or y == n or calculate(x, y) > k:
                return
            else:
                vistited[x][y] = 1
                final += 1
            dfs(x+1, y)
            dfs(x, y+1)
        dfs(0, 0)        
        return final
DYX
  • 31
  • 5

0 Answers0