开发者

Find a cycle in an undirected graph (boost) and return its vertices and edges

开发者 https://www.devze.com 2022-12-14 11:56 出处:网络
I need a functions thats find a cycle in an undirecte开发者_StackOverflow社区d graph (boost) and returns its vertices and edges. It needs only return the vertices/edges of one cycle in the graph.

I need a functions thats find a cycle in an undirecte开发者_StackOverflow社区d 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.


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.


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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消