我试图找到到给定节点的距离最短的节点,这就是我尝试过的。
import networkx as nx
G = nx.read_gpickle("Database/Pickle/test.gpickle")
targetcount = dict() #store number of reach to given node.
targetdistance = dict() #sum of distance to all of given node.
givennode = ['car', 'home', 'man']
#step1,find node that have path to givennode and store distance in dictionary
#by using single_source_dijkstra_path_length()
for source in givennode:
reachnode = nx.single_source_dijkstra_path_length(G, source, weight='cost')
#than store target node and distance from reachnode variable.
for target in reachnode:
if target in targetcount:
targetcount[target] += 1
targetdistance[target] += reachnode[target]
else:
targetcount[target] = 1
targetdistance[target] = reachnode[target]
minaverage = 999999999.99
finalword = ''
#step2, find average distance only node that can reach to all of given word.
for target in targetcount:
#if node have reach number equal to givennode amount.
if targetcount[target] == len(givennode):
averagedistance = targetdistance[target] / len(givennode)
if averagedistance < minaverage:
minaverage = averagedistance
finalword = target
print("Min average distance word :"+finalword)
通过执行这两个步骤,此代码大约需要9秒钟。
步骤1:查找从给定节点可以到达的节点,并存储到字典的距离。
第2步:通过仅计算可以到达所有给定节点的路径的节点,找到到给定节点的最小最小平均距离。
因此,有什么建议或其他方法可以更快地找到给定节点的最小平均距离。
谢谢