简体   繁体   English

在有向图中查找任何给定两个节点之间的所有可能最短路径时如何处理错误

[英]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.

相关问题 如何实现最短路径算法来查找python中任意两个给定城市之间的最短路径? - How to implement a shortest path algorithm to find shortest route between any two given cities of a graph in python? 来自两个节点之间所有最短路径的列表中的最大值 - Max from a list of all shortest paths between two nodes 在有向加权图中,有效地找到两个节点 A 和 B 之间穿过节点 X 的最短路径的成本 - In a directed, weighted graph, efficiently find the cost of the shortest path between two nodes A and B that traverses through a node X Networkx 在图中查找不同最短路径之间的公共节点 - 是否有替代解决方案? - Networkx finding common nodes between different shortest paths in a graph - Is there a alternate solution? 所有节点最短路径 - All Nodes shortest Paths 使用Python查找图形中两个顶点(节点)之间的所有路径 - Find all paths between two vertices (nodes) in a graph using Python 有向图中的深度:在距离给定节点 k 处查找节点 - Depth in Directed Graph: Finding nodes at k distance from a given node 在图中找到两个短语之间的最短路径 - finding shortest path between two phrases in a graph 查找图节点之间所有可能的连接组合 - Finding all possible combinations of connections between nodes of a graph 查找从所有节点到节点的最短路径的有效算法? - Efficent algorithm for finding the shortest paths from ALL nodes to a node?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM