移除n的内部环

2024-04-26 11:22:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个由许多自循环组成的大图。我试图移除所有的内部循环,这样我只剩下一个大的(外部)循环。有没有办法找到给定循环中的所有边?我尝试过使用graph.nodes_with_selfloops()和{},但这两种方法都没有让我走得太远。在


Tags: 方法withgraphnodes大图办法selfloops
1条回答
网友
1楼 · 发布于 2024-04-26 11:22:37

我找到了解决这个问题的方法networkx.算法图书馆:

import networkx as netx
import networkx.algorithms as al

# build graph
g = netx.DiGraph()
edges = [(1,2),(2,3),(3,4),(4,1),(1,2),(2,5),(5,3),(3,4),(4,1)]
g.add_edges_from(edges)

# find cycles
cycles = al.simple_cycles(g)

# assuming that the exterior cycle will contain the most nodes
for cycle in cycles:
    print len(cycle)

结果应为:

>>5

>>6

相关问题 更多 >