为什么第 12 行的深度优先搜索中的列表路径与路径的输出存在差异?

问题描述

这是 DFS 从源到目标的所有路径的代码,其中源 = 0,目标 = 图形大小 - 1。在第 12 行,为什么我不能简单地执行 res.append((path)),因为路径是已经有名单了吗?

from collections import defaultdict
class Solution:
    def allPathsSourceTarget(self,graph: List[List[int]]) -> List[List[int]]:
        adjlist = defaultdict(list)
        for i in range(len(graph)):
            adjlist[i].extend(graph[i])
        start = 0
        destination = len(graph) -  1
        res = []
        def dfs(node,path):
            nonlocal res
            if node == destination:
                res.append(list(path))
                return 
            if node in adjlist:
                for nextNode in adjlist[node]:
                    path.append(nextNode)
                    dfs(nextNode,path)
                    path.pop()
        dfs(0,[0])
        print(res)

解决方法

当您简单地传递路径时,它会传递对路径变量的引用。 本质上,您指的是原始路径变量。

list(path) 本质上会附加路径的浅拷贝作为新列表,因此不会反映对路径所做的更改。