网络节点=住宅单位、医院
网络边=权重等于长度的道路
如何计算每个住宅大厦到附近任何医院的最短距离?
我使用"nx.all_pairs_dijkstra_path_length“,然后过滤出每个住宅节点到医院节点的最短路径。有没有更快更好的方法?
发布于 2018-07-02 23:41:42
我猜你的边缘都是双向的。如果没有,那么在底部看到我修改过的算法,它反转了图形。
添加一个连接到所有医院的单一节点,其边缘权重为1
。找到从所有节点到添加节点的最短路径。这些路径中的下一个到最后一个节点是医院,从住宅区到医院的最短路径是在最后一个节点被截断的添加节点的路径。
G.add_node('auxiliary_node')
for hospital in hospitals:
G.add_edge(hospital, 'auxiliary_node', weight=1)
paths = nx.single_source_dijkstra_path(G,'auxiliary_node', weight='weight')
for path in paths:
if path[-1] is a residential node:
path.pop(0) #remove the first node, 'auxiliary_node'
#the remaining path is the shortest path from a hospital to
#path[-1].
#code here to reverse the path so it's a path from the
#residential block to its nearest hospital. And
#to process the path however you want.
else:
#it is a hospital. Ignore it.
如果权重不对称,则反转图。
H = G.reverse(copy=False) #without copy=False it would make a new copy of
#the graph. No need for that.
#same commands with H.
https://stackoverflow.com/questions/51144133
复制相似问题