特定のグラフからすべてのパスを見つける必要があります。今のところそれはできますが、再帰コードは効率的ではなく、グラフは非常に複雑です。したがって、より良いアルゴリズムが必要です。これまでの私のコードは次のとおりです。
def findLeaves(gdict):
# takes graph and find its leaf nodes
leaves = []
for endNode in gdict.iterkeys():
if not gdict[endNode]:
leaves.append(endNode)
return leaves
graphPaths = {}
def findPaths(gname, gdict, leave, path):
# finds all noncycle paths
if not gdict:
return []
temp = [node for node in gdict.iterkeys() if leave in gdict[node].keys() and node not in path]
if temp:
for node in temp:
findPaths(gname, gdict, node, [node] + path)
else:
graphPaths[gname].append(path)
# main
leaves = findLeaves(graph['graph'])
graphPaths['name'] = []
seenNodes = []
for leave in leaves:
findPaths(graph['name'], graph['graph'], leave, [leave])
開始ノードが 1 つしかないため、再帰関数が簡単になります。リーフが逆の順序でたどられる場合、すべてのリーフはそこに到着する必要があります。開始ノードは、着信エッジを持たないノードです。
私はたくさんのグラフを持っているので、それらを辞書に入れています。キーはグラフの名前です。これが私のデータの例です:
graph['graph']: {
0: {1: {}},
1: {2: {}, 3: {}},
2: {3: {}},
3: {4: {}},
4: {5: {}},
5: {6: {}},
6: {7: {}},
7: {6: {}, 5: {}}
}
graph['name'] = nameofthegraph
これらの構造は から取得したものpygraphviz
で、任意のノードからの発信エッジを単純に示しています。キーはノードで、値はノードへの発信エッジです。ただし、以下のような非常に複雑なグラフがある場合、このコードではすべてのパスを見つけることができませんでした。
あなたが提案できるより良いアルゴリズムはありますか?または、複雑なグラフ用にアルゴリズムを最適化する方法はありますか?