![](/img/trans.png)
[英]How to implement a shortest path algorithm to find shortest route between any two given cities of a graph in python?
[英]how to handle error when finding all possible shortest paths between any given two nodes in a directed graph
我有一個包含字符串節點的有向圖,我需要找到它的任何兩個給定節點之間的所有最短路徑。 由於某些節點之間沒有路徑, nx.shortest_path()
會出錯。 我嘗試了下面的代碼來處理錯誤並在遇到錯誤后強制程序繼續:
import networkx as nx
G2 = nx.DiGraph()
G2.add_edges_from([('A','B'),('A','C'),('A','D'),('A','F'),('F','G'),('F','H'),('H','I'),('A','I')])
N = list(G2.nodes)
nx.draw(G2, with_labels=1)
try :
for i in range(len(G2.nodes)) :
for j in range(len(G2.nodes)) :
print(nx.shortest_path(G2,N[i],N[j]))
print(i,j)
except Exception :
pass
問題是程序在 i=0, j=2 時停止。 導致這種情況的代碼有什么問題嗎?
在我看來,您只想要nx.all_pairs_shortest_path(G)
。 如果您需要考慮權重,或者當圖中的最短路徑存在聯系時,請小心。
如果這不完全符合您的需求,我還鼓勵您查看所有最短路徑算法的參考文檔,特別是在以 all_pairs_ 開頭的任何all_pairs_
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.