给定自定义边权值计算网络中的最短路径

2024-10-01 13:45:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图给每个边分配长度属性,并根据这些长度计算从节点X到节点Y的最短路径

但是,我不确定如何正确引用我在这部分代码中指定的长度属性:
nx.shortest_path(G,source='Dehli',target='Pune', weight = ?????)

代码:

import matplotlib.pyplot as plt
G = nx.Graph()
G.add_nodes_from(["Dehli","Ahmadabad","Kolkata",'Bangalore','Pune','Maduraj'])
G.add_edge('Dehli', 'Ahmadabad', length =890)
G.add_edge('Dehli', 'Kolkata', length =1422)
G.add_edge('Dehli', 'Bangalore', length =2168)
G.add_edge('Dehli', 'Pune', length =1450)
G.add_edge('Dehli', 'Maduraj', length = 2603)

G.add_edge('Ahmadabad', 'Kolkata', length =1902)
G.add_edge('Ahmadabad', 'Bangalore', length =1403)
G.add_edge('Ahmadabad', 'Pune', length =624)
G.add_edge('Ahmadabad', 'Maduraj', length =1807)
G.add_edge('Kolkata', 'Bangalore', length =1778)
G.add_edge('Kolkata', 'Pune', length =1782)
G.add_edge('Kolkata', 'Maduraj', length =2043)

G.add_edge('Bangalore', 'Pune', length =824)
G.add_edge('Bangalore', 'Maduraj', length =404)
G.add_edge('Pune', 'Maduraj', length =1195)



nx.draw(G,pos,node_color='k')

path = nx.shortest_path(G,source='Dehli',target='Pune')
path_edges = zip(path,path[1:])
nx.draw_networkx_nodes(G,pos,nodelist=path,node_color='g')
nx.draw_networkx_edges(G,pos,edgelist=path_edges,edge_color='g',width=7)
print(nx.shortest_path_length(G,source='Dehli',target='Pune'))
plt.show()

Tags: pathaddsourcetargetlengthnxdrawedge
1条回答
网友
1楼 · 发布于 2024-10-01 13:45:29

documentation开始,对shortest_path的调用形式为shortest_path(G, source=None, target=None, weight=None)

可选参数weight

weight (None or string, optional (default = None)) – If None, every edge has weight/distance/cost 1. If a string, use this edge attribute as the edge weight. Any edge attribute not present defaults to 1.

所以在你的例子中,称之为path = nx.shortest_path(G,source='Dehli',target='Pune', weight='length')。请注意,Networkx接受edge属性length=X,并将其存储在一个字典中,其键为'length'(字符串)和值为X。在

相关问题 更多 >