[英]how to handle error when finding all possible shortest paths between any given two nodes in a directed graph
I have a directed graph including string nodes and I need to find all shortest paths between any two given nodes of it.我有一个包含字符串节点的有向图,我需要找到它的任何两个给定节点之间的所有最短路径。 As between some of the nodes there is no path,
nx.shortest_path()
gives error.由于某些节点之间没有路径,
nx.shortest_path()
会出错。 I tried the code below to do handle the error and force the program to continue after facing an error:我尝试了下面的代码来处理错误并在遇到错误后强制程序继续:
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
the problem is that the program stops when it comes to i=0, j=2.问题是程序在 i=0, j=2 时停止。 Is anything wrong with the code causing this?
导致这种情况的代码有什么问题吗?
Looks to me like you just want nx.all_pairs_shortest_path(G)
.在我看来,您只想要
nx.all_pairs_shortest_path(G)
。 Be careful if you need to consider weights or if it matters when there are ties for shortest path in the graph.如果您需要考虑权重,或者当图中的最短路径存在联系时,请小心。
In case that doesn't exactly fit your needs I'd also encourage you to look at the reference documentation for all shortest path algorithms especially at any function that starts with all_pairs_
...如果这不完全符合您的需求,我还鼓励您查看所有最短路径算法的参考文档,特别是在以 all_pairs_ 开头的任何
all_pairs_
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.