What I need is to store all the edges OR vertices that make a cycle found on a graph. After two days of search on web, the closer that I got is the code that is not working:
struct CycleDetector : public dfs_visitor<> {
CycleDetector(std::vector<Vertex> p, std::vector<Vertex>& _cycle) : m_predecessor(p), cycle(_cycle) { }
void back_edge(Edge e, Graph const& g)
{
Vertex t = target(e, g);
Vertex c = source(e, g);
std::cout << "(" << t << "," << c << ")" << std::endl;
std::cout << "Predecessor: " << m_predecessor[c] << std::endl;
cycle.push_back(c);
do {
c = m_predecessor[c];
cycle.push_back(c);
} while(c != t);
}
protected:
std::vector<Vertex>& cycle;
std::vector<Vertex> m_predecessor;
};
int main()
{
//after a routine to create the graph and add_edges
std::vector<Vertex> cycle;
std::vector<Vertex> p(num_vertices(g1));
CycleDetector vis(p, cycle);
depth_first_search(g1, visitor(vis));
for (int i=0; i<cycle.size(); i++)
std::cout << cycle[i] << ", ";
std::cout << std::endl;
Here is the output of the program. It's a spanning tree with max degree 2. I'm adding an edge on E and H vertices, to proposely create a cycle. I need to detect this cycle and return all the vertices or edges that form it.
Thanks.