ノード "a" とノード "o" からすべての LCA ノードを取得したいと考えています。
この DiGraph では、ノード "l" とノード "m" が LCA ノードです。
以下はコードです。
import networkx as nx
def calc_length(Graph, node1, node2, elem):
length1 = nx.shortest_path_length(Graph, node1, elem)
length2 = nx.shortest_path_length(Graph, node1, elem)
length_sum = length1 + length2
return length_sum
G = nx.DiGraph() #Directed graph
G.add_nodes_from(["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p"])
edges = [("a","b"),("b","c"),("b","d"),("a","e"),("a","h"),("e","f"),("e","g"),("e","i"),("h","l"),("h","m"),("g","j"),("o","p"),("o","n"),("n","m"),("n","l"),("n","k"),("p","j"),]
G.add_edges_from([(e[0], e[1]) for e in edges])
preds_1 = nx.bfs_predecessors(G, "a")
preds_2 = nx.bfs_predecessors(G, "o")
common_preds = set([n for n in preds_1]).intersection(set([n for n in preds_2]))
common_preds = list(common_preds)
dic ={}
for elem in common_preds:
length_sum = calc_length(G, "a", "o", elem)
dic[elem] = length_sum
min_num = min(dic.values())
for k, v in sorted(dic.items(), key=lambda x:x[1]):
if v != min_num:
break
else:
print k, v
実行速度を速くしたい。
前述の方法以外で問題を解決するためのより良い方法があれば教えてください。
あなたの助けに感謝します。