簡體   English   中英

在Networkx中選擇最短路徑的明確性

[英]The unambiguity of choosing the shortest path in Networkx

我有一個圖:

在此處輸入圖片說明

為什么使用最短路徑的函數后:

nx.shortest_path(g, 0, 6)

為什么輸出路徑是[0, 3, 6] 為什么不[0, 2, 6] 在上述情況下,算法shortest_path()的路徑[0, 3, 6]的選擇是否始終是唯一的?

@ jon-clements在對該問題的評論中具有正確答案。 如果有一條以上的最短路徑,則函數networkx.shortest_path()將返回其中一條。 您獲得的具體路徑取決於數據如何存儲在networkx圖形數據結構(基於Python字典)中,並且不能保證是確定性的。 您可以根據需要獲得所有最短路徑,甚至可以對它們進行排序以提供穩定的順序-例如

In [1]: import networkx as nx

In [2]: G = nx.Graph({0: [3, 2], 2: [6, 4], 3: [5, 6]})

In [3]: nx.shortest_path(G, 0, 6)
Out[3]: [0, 2, 6]

In [4]: list(nx.all_shortest_paths(G, 0,6))
Out[4]: [[0, 3, 6], [0, 2, 6]]

In [5]: sorted(nx.all_shortest_paths(G, 0,6))
Out[5]: [[0, 2, 6], [0, 3, 6]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM