我有一個(可能)簡單的圖遍歷問題。我是一個使用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()
我覺得我的骨頭裏沒有必要傳遞這個「路徑」列表......我應該能夠使用調用堆棧來跟蹤這些信息,但是我無法弄清楚......怎麼可能有人啓發我如何解決這個問題遞歸使用堆棧來跟蹤路徑?
在python中實現圖的強制性閱讀http://www.python.org/doc/essays/graphs/ –
可能的答案是:http:// stackoverflow。com/questions/6061744/how-to-get-value-of-arguments-in-functions-at-stack – GL770
@ GL770對於這樣一種簡單的圖算法,直接使用'inspect'模塊查找堆棧看起來並不優雅我。 –