【发布时间】:2025-12-30 21:55:06
【问题描述】:
我有以下递归函数 - 该函数可以很好地打印出树/图的所有路径。但是尝试将ROUTES 添加为全局变量并附加到它会导致一堆空的嵌套列表:
[[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [],...等
我正在寻找使用全局变量的更好解决方案和存储路径的更好解决方案,这就是我的功能:
def printAllPathsUtil(self, u, d, visited, path):
# Mark the current node as visited and store in path
visited[u] = True
path.append(u)
# If current vertex is same as destination, then print
# current path[]
if u == d:
print(path)
ROUTES.append(path)
else:
# If current vertex is not destination
# Recur for all the vertices adjacent to this vertex
for i in self.graph[u]:
if visited[i] == False:
self.printAllPathsUtil(i, d, visited, path)
# Remove current vertex from path[] and mark it as unvisited
path.pop()
visited[u] = False
【问题讨论】:
-
ROUTES.append(i for i in path)好像输出[<generator object Graph.printAllPathsUtil.<locals>.<genexpr> at 0x03B27F30>, <generator object Graph.printAllPathsUtil.<locals>.<genexpr> at 0x03B27F70>, <generator object Graph.printAllPathsUtil.<locals>.
标签: python python-3.x list recursion