python - 为什么在第 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)
本质上会将路径的浅表副本附加为新列表,因此不会反映对路径所做的更改。
推荐阅读
- r - R 中的简单正则表达式转义 "Mr\\."
- firebase - 使用 vue.js 和 vuex 在 FireBase 中编辑和更新日期?
- r - 谷歌地图使用ggmap()向北偏移?
- python - SyntaxError: 无效的语法 re_path(r'^connect/(?P
.+)/(?P \d+)/$' - nginx - 使用 nginx ffmpeg 问题转码流
- python - 如何使用 Beautiful Soup 找到带有特定文本的 href 链接?
- mysql - 错误代码:1054。“字段列表”中的未知列“喜欢”
- java - 当我自己使用参数字符串抛出异常时,究竟会发生什么?什么时候调用 toString 方法?
- android - 根据月份和年份对多视图类型 RecyclerView 进行排序
- python - 如何使用张量流有效地提取给定长度的所有切片