Finding all cycles in an undirected graph

3,028 views
Skip to first unread message

Fabian

unread,
Jan 25, 2016, 11:19:33 PM1/25/16
to networkx-discuss
Dear networkx-discuss,

I searched for this problem within this group for a while but couldn't find a satisfying solution.

Given an undirected graph G, how can I find all cycles in G?
I believe that I should use cycle_basis. The documentation says

A basis for cycles of a network is a minimal collection of cycles such that any cycle in the network can be written as a sum of cycles in the basis. Here summation of cycles is defined as “exclusive or” of the edges.

How can I enumerate all sums of cycles in the basis and hence enumerate all cycles?
I would like to use as much from the networkx package as possible, and hopefully there is an easy way.

Thank you for your help!
-Fabian

Daniel Schult

unread,
Jan 26, 2016, 1:30:56 AM1/26/16
to networkx...@googlegroups.com
Maybe you can explain why you want to do such a thing. Do you mean all simple cycles? (There's a stackoverflow question about that and a NetworkX function to provide it  

To show the issue with the question, let's say that you have two cycles called a and b in the basis. Then other cycles can be ab, aa, aba, abba, baba, ..., babababababbbbababbbabababababb... :}   without any restriction you can keep going around a as long as you want before passing to b and going around that cycle.

I think a cycle_basis is enough for most questions and simple_cycles should fill in most others. Does this help?

--
You received this message because you are subscribed to the Google Groups "networkx-discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to networkx-discu...@googlegroups.com.
To post to this group, send email to networkx...@googlegroups.com.
Visit this group at https://groups.google.com/group/networkx-discuss.
For more options, visit https://groups.google.com/d/optout.

Fabian

unread,
Jan 26, 2016, 3:39:32 AM1/26/16
to networkx-discuss
Sorry, yes, I mean all simple cycles.
The reason I dismissed simple_cycles was that it is defined for directed graphs.
But I could just use

G=nx.Graph()
#...
H=G.to_directed()
simple_cycles=list(nx.simple_cycles(H))

Correct? Thanks for your help!

Daniel Schult

unread,
Jan 26, 2016, 9:19:26 AM1/26/16
to networkx...@googlegroups.com
On Tue, Jan 26, 2016 at 3:39 AM, Fabian <fabian.r...@gmail.com> wrote:
Sorry, yes, I mean all simple cycles.
The reason I dismissed simple_cycles was that it is defined for directed graphs.
But I could just use

G=nx.Graph()
#...
H=G.to_directed()
simple_cycles=list(nx.simple_cycles(H))

Correct? Thanks for your help!

Yes -- The G.to_directed() replaces each undirected edge with two directed edges. You can manually create other replacements, but I think this is what you probably want. :)  
Reply all
Reply to author
Forward
0 new messages