UnboundLocalError:赋值前引用的局部变量“computed_matrix”

2024-04-29 04:38:03 发布

您现在位置:Python中文网/ 问答频道 /正文

class Solution(object):
    def longestIncreasingPath(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: int
        """
        # dfs
        computed_matrix = [[0 for j in range(len(matrix[i]))] for i in range(len(matrix))]
        result = 0

        def dfs(i, j):
            if computed_matrix[i][j]:
                return computed_matrix[i][j]

            current = matrix[i][j]
            if i > 0 and matrix[i - 1][j] > current:
                computed_matrix = max(computed_matrix[i][j], dfs(i - 1, j))

            if j < len(matrix[i]) - 1 and matrix[i][j + 1] > current:
                computed_matrix[i][j] = max(computed_matrix[i][j], dfs(i, j + 1))

            if i < len(matrix) - 1 and matrix[i + 1][j] > current:
                computed_matrix[i][j] = max(computed_matrix[i][j], dfs(i + 1, j))

            if j > 0 and matrix[i][j - 1] > current:
                computed_matrix[i][j] = max(computed_matrix[i][j], dfs(i, j - 1))

            computed_matrix[i][j] += 1
            return computed_matrix[i][j]

        # memo/cache
        for i in range(len(matrix)):
            for j in range(len(matrix[i])):
                result = max(result, dfs(i, j))
        return result


if __name__ == '__main__':
    test_one = Solution()
    matrix = [[3, 4, 5], [3, 2, 6], [2, 2, 1]]
    test_one.longestIncreasingPath(matrix)

我有一个主函数longestIncreasingPath(),在其中调用子dfs函数,但它无法解析dfs函数内的计算矩阵参数函数,但它能够解析同一范围内的矩阵参数。问题是什么

我知道我在某种程度上使用了另一个未嵌套的函数,并使其与self一起工作,但是下面的代码的当前问题是什么


Tags: and函数inforlenreturnifrange