Skip to main content
 首页 » 编程设计

Python 网络 : How to check if only a single simple path exists between two nodes

2025年05月04日58oomusou

我正在使用 networkx.all_simple_paths(G,source,dest) 找出两个节点之间的所有可能路径。我返回多个列表。

这是我的代码片段:

for path in (nx.all_simple_paths(G,source=node1,target=node2): 
         print path  

这给了我存储路径的多个列表。 我需要找出给定的一对节点之间是否只有一条路径。

我该怎么做?

谢谢。

请您参考如下方法:

不是绝对最干净的,但这里有一个函数会查看迭代器。如果没有第一个元素,则返回 False。如果有第一个元素(即有路径),但没有第二个元素,则返回 True。如果有第二个(即不止一个路径),它返回 False。它从不检查是否还有更多内容。

def simple_path(G,source,target): 
    iterator = nx.all_simple_paths(G,source=source,target=target) 
    try: 
        first_path = next(iterator) 
    except StopIteration: 
        return False 
    try: 
        second_path = next(iterator) 
    except StopIteration: 
        return True 
    return False 

样本运行:

In [3]: G= nx.Graph() 
 
In [4]: G.add_edges_from([(1,2),(1,3),(2,3),(3,4)]) 
 
In [5]: simple_path(G,1,2) 
Out[5]: False 
 
In [6]: simple_path(G,1,3) 
Out[6]: False 
 
In [7]: simple_path(G,3,4) 
Out[7]: True 
 
In [8]: simple_path(G,1,4) 
Out[8]: False