我需要查找給定圖的所有路徑。我現在可以這樣做,但是我的遞歸代碼效率不高,我的圖形也非常複雜。因此我需要一個更好的算法。這裏是我的代碼到目前爲止,查找給定圖python的所有路徑
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])
只有一個起始節點,這使得事情更容易遞歸功能。如果葉子以相反的順序跟隨,每片葉子需要到達那裏。起始節點是沒有傳入邊緣的節點。
我有很多圖,所以我把它們保存在字典中。鍵是圖形的名稱。下面是我的數據的示例:
graph['graph']: {
0: {1: {}},
1: {2: {}, 3: {}},
2: {3: {}},
3: {4: {}},
4: {5: {}},
5: {6: {}},
6: {7: {}},
7: {6: {}, 5: {}}
}
graph['name'] = nameofthegraph
這些結構是從pygraphviz
截取,它僅僅示出了從任何節點傳出邊緣。鍵是節點,值是節點的輸出邊。但是,當我有如下複雜圖形時,此代碼無法找到所有路徑。
有沒有更好的算法,你可以建議?或有什麼辦法來優化我的算法複雜的圖形?
發生此問題http://codereview.stackexchange.com/爲@sundarnatarajСундар感謝優化和效率 –
我不知道該網站。 [問題](http://codereview.stackexchange.com/questions/55767/finding-all-paths-from-given-graph-python) – genclik27
它確定。你會得到很好的評論,如何優化和效率 –