我有一个包含许多自循环的大图。我试图删除所有内部循环,以便我只留下一个大(外部)循环。有没有办法找到给定循环中的所有边?我尝试过使用graph.nodes_with_selfloops()
和graph.selfloop_edges
,但都没有让我走得太远。
答案 0 :(得分:2)
我找到了一种使用networkx.algorithms库解决这个问题的方法:
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