制作一张dijkstra表

时间:2014-11-13 15:12:59

标签: python python-2.7 network-programming ipython ipython-notebook

我正在尝试使用networkx创建一个包含两列的表,一列具有距离,另一列具有从所选节点中移除的节点。

因此,在距离下,应该有3行0,1和2.并且在节点下应该有每个节点,例如从X中移除的1个节点应该在距离1的行中。

我尝试了这个并且它提供了正确的距离和节点,但我不知道如何编码它所以它将显示我希望它显示的方式。

import networkx as nx
G = nx.Graph()
V = ["A", "B", "C", "D", "X"]
E = [("A", "B"), ("B", "C"), ("C", "D"), ("X", "A"), ("X", "D")]
G.add_nodes_from(V)
G.add_edges_from(E)

distance = []
nodes = []
def shortestPath(node):
  print "Distance Nodes"
    for i in G.nodes():
       for j in G.nodes():
          if j not in nodes:
            nodes.append(j)
            print "%s\t%s" % ((nx.shortest_path_length(G, node, j), j))                  

shortestPath("X")

它显示如下

Distance Nodes
1        A
2        X
1        C
0        B
2        D

1 个答案:

答案 0 :(得分:0)

您需要反转最短路径输出生成的字典。 这是一种方法:

import networkx as nx                                                              
from collections import defaultdict                                                
E = [("A", "B"), ("B", "C"), ("C", "D"), ("X", "A"), ("X", "D")]                   
G = nx.Graph(E)                                                                    
# compute single source shortest path length                                       
spl = nx.shortest_path_length(G, source='X')                                       

# invert dictionary with keys as distance and values as list of nodes              
length = defaultdict(list)                                                         
for n,l in spl.items():                                                            
    length[l].append(n)                                                            

# print inverted dictionary                                                        
for l in sorted(length):                                                           
    print l,length[l]