网络节点=居民单元,医院
网络边缘=权重等于长度的道路
如何计算每个居民区到附近任何医院之间的最短距离?
我使用了“ nx.all_pairs_dijkstra_path_length”,然后过滤了每个居民节点到医院节点的最短路径。有没有更快更好的方法?
答案 0 :(得分:0)
我假设您的边缘都是双向的。如果没有,那么请参阅我在底部修改过的算法,以反转图形。
添加一个边缘权重为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.