我有一个(可能)简单的图遍历问题。我是使用 networkx 作为我的图形数据结构的图形新手。我的图表总是这样:
0
1 8
2 3 9 10
4 5 6 7 11 12 13 14
我需要返回从根节点到给定节点的路径(例如,path(0, 11)
应该 return [0, 8, 9, 11]
)。
我有一个解决方案,它通过传递一个增长和缩小的列表来跟踪遍历树时路径的样子,最终在找到目标节点时返回:
def VisitNode(self, node, target, path):
path.append(node)
# Base case. If we found the target, then notify the stack that we're done.
if node == target:
return True
else:
# If we're at a leaf and it isn't the target, then pop the leaf off
# our path (backtrack) and notify the stack that we're still looking
if len(self.neighbors(node)) == 0:
path.pop()
return False
else:
# Sniff down the next available neighboring node
for i in self.neighbors_iter(node):
# If this next node is the target, then return the path
# we've constructed so far
if self.VisitNode(i, target, path):
return path
# If we've gotten this far without finding the target,
# then this whole branch is a dud. Backtrack
path.pop()
我从骨子里觉得没有必要传递这个“路径”列表......我应该能够使用调用堆栈跟踪该信息,但我不知道如何......有人可以启发我如何使用堆栈递归地解决这个问题来跟踪路径?