Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find circular relations in a graph with Python and Networkx?

Consider I have the following graph:

A -> B
B -> C
C -> D
C -> A

What is the easiest way to find that A -> B -> C -> A is a circular relation? Is there such a function already built into NetworkX or another easy to use Python library?

like image 637
Buttons840 Avatar asked Feb 21 '12 18:02

Buttons840


2 Answers

networkx.simple_cycles does this for you.

>>> import networkx as nx
>>> G = nx.DiGraph()
>>> G.add_edge('A', 'B')
>>> G.add_edge('B', 'C')
>>> G.add_edge('C', 'D')
>>> G.add_edge('C', 'A')
>>> nx.simple_cycles(G)
[['A', 'B', 'C', 'A']]
like image 178
Fred Foo Avatar answered Oct 06 '22 01:10

Fred Foo


Use Depth-First Search to detect cycles in a graph.

like image 34
Sufian Latif Avatar answered Oct 05 '22 23:10

Sufian Latif