Warning

This documents an unmaintained version of NetworkX. Please upgrade to a maintained version and see the current NetworkX documentation.

networkx.algorithms.cycles.find_cycle¶

find_cycle(G, source=None, orientation=None)[source]

Returns a cycle found via depth-first traversal.

The cycle is a list of edges indicating the cyclic path. Orientation of directed edges is controlled by orientation.

Parameters: G (graph) – A directed/undirected graph/multigraph. source (node, list of nodes) – The node from which the traversal begins. If None, then a source is chosen arbitrarily and repeatedly until all edges from each node in the graph are searched. orientation (None | ‘original’ | ‘reverse’ | ‘ignore’ (default: None)) – For directed graphs and directed multigraphs, edge traversals need not respect the original orientation of the edges. When set to ‘reverse’ every edge is traversed in the reverse direction. When set to ‘ignore’, every edge is treated as undirected. When set to ‘original’, every edge is treated as directed. In all three cases, the yielded edge tuples add a last entry to indicate the direction in which that edge was traversed. If orientation is None, the yielded edge has no direction indicated. The direction is respected, but not reported. edges – A list of directed edges indicating the path taken for the loop. If no cycle is found, then an exception is raised. For graphs, an edge is of the form (u, v) where u and v are the tail and head of the edge as determined by the traversal. For multigraphs, an edge is of the form (u, v, key), where key is the key of the edge. When the graph is directed, then u and v are always in the order of the actual directed edge. If orientation is not None then the edge tuple is extended to include the direction of traversal (‘forward’ or ‘reverse’) on that edge. directed edges NetworkXNoCycle – If no cycle was found.

Examples

In this example, we construct a DAG and find, in the first call, that there are no directed cycles, and so an exception is raised. In the second call, we ignore edge orientations and find that there is an undirected cycle. Note that the second call finds a directed cycle while effectively traversing an undirected graph, and so, we found an “undirected cycle”. This means that this DAG structure does not form a directed tree (which is also known as a polytree).

>>> import networkx as nx
>>> G = nx.DiGraph([(0, 1), (0, 2), (1, 2)])
>>> try:
...    nx.find_cycle(G, orientation='original')
... except:
...    pass
...
>>> list(nx.find_cycle(G, orientation='ignore'))
[(0, 1, 'forward'), (1, 2, 'forward'), (0, 2, 'reverse')]