(おそらく) 単純なグラフ トラバーサルの質問があります。私はグラフのデータ構造として 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()
この「パス」リストを渡す必要がないことを骨の髄まで感じています...コールスタックを使用してその情報を追跡できるはずですが、方法がわかりません...誰かが啓発できますかパスを追跡するためにスタックを使用してこの問題を再帰的に解決する方法について教えてください。