首页 > 解决方案 > 为什么在第 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)

标签: pythonpython-3.xrecursiondata-structuresgraph

解决方案


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

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


推荐阅读