UnboundLocalError: local variable 'x' referenced before assignment for one variable whilst other works in Python

UnboundLocalError: local variable 'x' referenced before assignment for one variable whilst other works in Python

为什么我可以在 dfs 函数中使用 copy_matrix 而在 cur_max 的赋值错误之前引用局部变量?

class Solution:
    def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
        rows, columns = len(matrix), len(matrix[0])
        copy_matrix = {}
        cur_max = 0
        
        def dfs(r, c, prev):
            if (r < 0 or c < 0 or
                r == rows or c == columns or
                matrix[r][c] <= prev):
                return 0
            
            if (r, c) in copy_matrix:
                return copy_matrix[(r, c)]
            
            max_length = 0
            max_length = max(max_length, 1 + dfs(r + 1, c, matrix[r][c]))
            max_length = max(max_length, 1 + dfs(r - 1, c, matrix[r][c]))
            max_length = max(max_length, 1 + dfs(r, c + 1, matrix[r][c]))
            max_length = max(max_length, 1 + dfs(r, c - 1, matrix[r][c]))
            copy_matrix[(r, c)] = max_length
            cur_max = max(cur_max, copy_matrix[(r, c)])
            
            return max_length
        
        for r in range(rows):
            for c in range(columns):
                dfs(r, c, -1)
        
        return max(copy_matrix.values())

这是我得到的

UnboundLocalError: local variable 'cur_max' referenced before assignment
    cur_max = max(cur_max, copy_matrix[(r, c)])
Line 22 in dfs (Solution.py)
    dfs(r, c, -1)
Line 28 in longestIncreasingPath (Solution.py)
    ret = Solution().longestIncreasingPath(param_1)
Line 49 in _driver (Solution.py)
    _driver()
Line 60 in <module> (Solution.py)

因为copy_matrix没有局部变量,所以它引用第6行的nonlocal变量,即copy_matrix = {},而cur_max是在第 24 行被定义为局部变量,即 cur_max = max(cur_max, copy_matrix[(r, c)]),它引用 copy_matirxrowscolumns 的非局部变量,但它引用 [=] 的局部变量14=] 因为它在函数中被定义并且在赋值之前被引用。你可能想要做的是这个

def dfs(r, c, prev):
    nonlocal cur_max
    if (r < 0 or c < 0 or
        r == rows or c == columns or
        matrix[r][c] <= prev):
        return 0
    
    if (r, c) in copy_matrix:
        return copy_matrix[(r, c)]
    
    max_length = 0
    max_length = max(max_length, 1 + dfs(r + 1, c, matrix[r][c]))
    max_length = max(max_length, 1 + dfs(r - 1, c, matrix[r][c]))
    max_length = max(max_length, 1 + dfs(r, c + 1, matrix[r][c]))
    max_length = max(max_length, 1 + dfs(r, c - 1, matrix[r][c]))
    copy_matrix[(r, c)] = max_length
    cur_max = max(cur_max, copy_matrix[(r, c)])
    
    return max_length

read more