循环检测#

此示例演示了如何使用 nx.find_cycle 在图中查找单个任意循环。

其他函数,如 nx.simple_cyclesnx.cycle_basis 可用于查找所有循环或循环基。

plot cycle detection
[(2, 3, 'forward'), (3, 4, 'forward'), (4, 2, 'forward')]

import networkx as nx
import matplotlib.pyplot as plt

# Create a simple directed graph with a cycle
G = nx.DiGraph([(1, 2), (2, 3), (3, 4), (4, 2), (3, 5), (3, 2), (1, 5)])

# Draw the graph
pos = nx.spring_layout(G, seed=8020)
nx.draw(G, pos, with_labels=True)

# The `orientation` parameter can be used to determine how directed edges are
# treated and the reporting of edge direction in the cycle
cycle = nx.find_cycle(G, orientation="original")
print(cycle)

# Highlight the cycle in red
nx.draw_networkx_edges(G, pos, edgelist=cycle, edge_color="r", width=2)
plt.show()

脚本总运行时间: (0 分钟 0.084 秒)

由 Sphinx-Gallery 生成的画廊