【发布时间】:2016-04-27 13:20:59
【问题描述】:
在3x3 网络中,我希望能够确定任意两个节点之间的所有最短路径。然后,对于网络中的每个节点,我想计算有多少最短路径通过一个特定节点。
这需要使用nx.all_shortest_paths(G,source,target) 函数,该函数返回generator。这与使用nx.all_pairs_shortest_path(G) 不同,正如here 所建议的那样。不同之处在于,在前一种情况下,该函数计算任意两个节点之间的所有最短路径,而在后一种情况下,它只计算同一对节点之间的一个最短路径节点。
鉴于我需要考虑所有最短路径,我想出了以下脚本。这就是我生成正在使用的网络的方式:
import networkx as nx
N=3
G=nx.grid_2d_graph(N,N)
pos = dict( (n, n) for n in G.nodes() )
labels = dict( ((i, j), i + (N-1-j) * N ) for i, j in G.nodes() )
nx.relabel_nodes(G,labels,False)
inds=labels.keys()
vals=labels.values()
inds.sort()
vals.sort()
pos2=dict(zip(vals,inds))
nx.draw_networkx(G, pos=pos2, with_labels=False, node_size = 15)
这就是我打印任意两个节点之间所有最短路径的方式:
for n in G.nodes():
for j in G.nodes():
if (n!=j): #Self-loops are excluded
gener=nx.all_shortest_paths(G,source=n,target=j)
print('From node '+str(n)+' to '+str(j))
for p in gener:
print(p)
print('------')
结果是从节点x 到节点y 的路径,其中仅包括沿途的节点。我得到的摘录是:
From node 0 to 2 #Only one path exists
[0, 1, 2] #Node 1 is passed through while going from node 0 to node 2
------
From node 0 to 4 #Two paths exist
[0, 1, 4] #Node 1 is passed through while going from node 0 to node 4
[0, 3, 4] #Node 3 is passed through while going from node 0 to node 4
------
...continues until all pairs of nodes are covered...
我的问题:如何修改最后一个代码块以确保我知道总共有多少最短路径通过每个节点?根据我提供的摘录结果,节点1经过2次,节点3经过1次(不包括开始和结束节点)。这个计算需要进行到底,才能算出最终通过每个节点的路径数。
【问题讨论】:
-
如果将问题限制为二维网格图,则可以解析计算任意两点之间的最短路径数。如果您仍然对这个问题感兴趣,我可以发布计算作为答案。
标签: python graph graph-algorithm networkx shortest-path