我有一个答案,解释了在另一篇文章中使用 Python 和 networkX 在有向图中查找所有循环的简单方法。在有向图中查找所有循环
该解决方案将输出一个列表,其中包含有向图的所有循环。
您可以使用此输出找到最长的循环,如下所示:
import networkx as nx
# Create Directed Graph
G=nx.DiGraph()
# Add a list of nodes:
G.add_nodes_from(["1","2","3","4","5","6","7","9"])
# Add a list of edges:
G.add_edges_from([("7","9"),("1","2"),("2","3"),("3","1"),("3","4"),("4","5"),("5","1"),("5","6"),("6","7"),("7","2")])
#Return a list of cycles described as a list o nodes
all_cycles = list(nx.simple_cycles(G))
#Find longest cycle
answer = []
longest_cycle_len = 0
for cycle in all_cycles:
cycle_len = len(cycle)
if cycle_len>longest_cycle_len:
answer =cycle
longest_cycle_len = cycle_len
print "Longest Cycle is {} with length {}.".format(answer,longest_cycle_len)
答:最长的循环是 ['3', '4', '5', '6', '7', '2'],长度为 6。
如果您觉得有趣,也请支持原始答案。这是一个有很多答案的旧讨论,它将有助于提出新的解决方案。