我有一个(可能)简单的图形遍历问题.我是使用networkx作为图形数据结构的图形新手.我的图总是这样:
0
1 8
2 3 9 10
4 5 6 7 11 12 13 14
我需要返回从根节点到给定节点的路径(例如,path(0,11)应该返回[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()
我感到骨子里没有必要传递这个“路径”列表…我应该能够使用调用堆栈来跟踪该信息,但是我不知道如何…有人可以启发一下我如何使用堆栈来递归地解决路径问题?