关于如何计算图中两个节点之间的欧式距离的任何建议?使用此图:
nodes = [('B','D'), ('D','E'), ('D','A'), ('E','A'), ('E','C'), ('A','C')]
graph = nx.Graph(nodes)
nx.draw(graph, node_color = 'red', with_labels = True)
我尝试使用
nx.shortest_path(graph, source, target)
使用nx.shortest_path()给我以下错误:
TypeError: argument of type 'NoneType' is not iterable
我知道Dijkstra的算法,但我只想计算欧几里得距离。有什么建议?
您应该能够像这样计算最短距离:
dist = nx.shortest_path(graph, 'A', 'B')
dist的长度为您提供了节点A和B之间的步数:
len(dist)
# returns 3
计算欧几里得距离将要求节点具有与之关联的某种坐标。
例如存储在属性中coords
:
# adding coordinates:
for n in graph.nodes:
graph.nodes[n]['coords'] = np.random.rand(2)
def get_euclidean_distance(graph, source, dest):
x1, y1 = graph.nodes[source]['coords']
x2, y2 = graph.nodes[dest]['coords']
return np.sqrt((x1-x2)**2 + (y1-y2)**2)
get_euclidean_distance(graph, 'A', 'B')
# out 0.14540849196243125
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句