tags:

views:

553

answers:

3

I need a functions thats find a cycle in an undirected graph (boost) and returns its vertices and edges. It needs only return the vertices/edges of one cycle in the graph. My question is - what is the best way to do this using with boost? I am not experienced using it.

+2  A: 

Generally you can do this with a depth first search. I'm not intimately familiar with boost's graphing facilities but this page will give you an overview of the algorithm.

Pace
+3  A: 

I do not know Boost, but here is the answer from S.O. at a conceptual level:

Here is my guess: walk through the graph using BFS. On every node note its "depth" and add a reference to a "parent" (should be only one even if there are many cycles). Once you discover that a link from A to B creates a cycle (because B is already colored), then: 1) Backtrack from A back to the root, save the edges / vertices along the way. 2) Backtrack from B back to the root, save the edges / vertices along the way. 3) Add A, B, AB 4) "Sort" to restore the proper order. Consider using a LIFO (stack) for 1) and a FIFO for 2)

I hope this helps.

Hamish Grubijan
Amir Rachum
EDIT: Both LIFO and FIFO can be of use.
Hamish Grubijan
+1  A: 

If you want to find a cycle, then using depth first search should do just fine. The DFS visitor has a back_edge function. When it's called, you have an edge in the cycle. You can then walk the predecessor map to reconstruct the cycle. Note that:

  • There's the strong_components function, to find, well, strong components
  • Finding all cycles, as opposed to a cycle, is much harder problem, and I believe Boost.Graph does not have a implementation for that at present
Vladimir Prus
Thanks, I will try it. Can you expand a bit about the predecessor map?Regarding the notes:* I am looking for a cycle in an undirected graph, so strong_components does not help me. * I am only looking for one cycle at a time (the point is to fix the cycle in a certain way and then recheck, fixing any other cycles, etc.)
Amir Rachum
Predecessor map is a parameter you can pass to depth_first_search that tells, for every vertex 'u', which vertex 'v' DFS came from when it first say 'v'. So, you you see back edge from u' to u, you should first look in predecessor map for u' to find u'', then lookup u'' to find u''', etc, until you get a vertex that is equal to u.If you look at libs/graph/example/bfs.cpp, you'll see how you can ask for a predecessor map to be created -- it works the same for dfs and bfs.
Vladimir Prus