find_cycle

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

Returns the edges of a cycle found via a directed, depth-first traversal.

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 (‘original’ | ‘reverse’ | ‘ignore’) – For directed graphs and directed multigraphs, edge traversals need not respect the original orientation of the edges. When set to ‘reverse’, then every edge will be traversed in the reverse direction. When set to ‘ignore’, then each directed edge is treated as a single undirected edge that can be traversed in either direction. For undirected graphs and undirected multigraphs, this parameter is meaningless and is not consulted by the algorithm.
Returns:

edges – A list of directed edges indicating the path taken for the loop. If no cycle is found, then edges will be an empty list. 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 ‘ignore’, then an edge takes the form (u, v, key, direction) where direction indicates if the edge was followed in the forward (tail to head) or reverse (head to tail) direction. When the direction is forward, the value of direction is ‘forward’. When the direction is reverse, the value of direction is ‘reverse’.

Return type:

directed edges

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:
...    find_cycle(G, orientation='original')
... except:
...    pass
...
>>> list(find_cycle(G, orientation='ignore'))
[(0, 1, 'forward'), (1, 2, 'forward'), (0, 2, 'reverse')]