2017-08-10 106 views

回答

1

假設你的圖是G和源節點爲source,那麼你可以使用single_source_dijkstra_path_length獲得路徑長度如下:

>>> source_path_lengths = networkx.single_source_dijkstra_path_length(G, source) 
>>> for (v, l) in source_path_lengths.iteritems(): 
     if l == 2: 
      print v 
+0

謝謝您的回覆。這種方法很好,但不適合計算整個圖的節點。這種方法需要計算其他距離,如3和4,這是不使用和浪費時間。有沒有浪費這些時間的有效方法。提前致謝。 – SunWJ

+0

@SunWJ您總是可以使用關鍵字參數'cutoff'將搜索降低到小於或等於2的路徑。此外,根據您的圖形是否加權,您可以使用'single_source_shortest_path_length'(非加權)。 – rodgdor

+0

非常感謝你 – SunWJ

1

好了,你可以指定「截止」參數設置爲「2」從Single Source Shortest Path - Networkx的文檔可以看出。所以基本上算法找到路徑,直到路徑長度爲< =截止。

import networkx as nx 

G = nx.path_graph(5) 

path = nx.single_source_shortest_path_length(G ,source=src_vertex,cutoff=2) 

然後,您可以使用以下方法來頂點列表在< = 2的距離源

print path.keys() 
#output : [0, 1, 2, 3, 4] 

或者你可以打印字典本身得到完全的源之間的距離,高達長度< =截止

print vertex_list 
#Output : {0: 0, 1: 1, 2: 2} 

頂點可以相應地改變的「臨界」值根據自己的需要。

+0

非常感謝你! – SunWJ

相關問題