I was trying to use the code from this thread: Boost DFS back_edge, to record the cycles in an undirected graph. To do this I need to store the predecessors
for each dfs tree when it finds a back_edge. Since this is an undirected graph I think we can not use directly on_back_edge()
from EventVisitor Concept. So I was thinking to record the predecessors in the void back_edge()
method of below code. But I am not sure how to do this and return the cycle vertices.
Here is the code and the part I added for recording predecessors:
#include <boost/config.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/depth_first_search.hpp>
namespace {
using namespace boost;
typedef adjacency_list<vecS, vecS, undirectedS, no_property,
property<edge_weight_t, int> > Graph;
typedef graph_traits<Graph>::edge_descriptor Edge;
typedef std::set<Edge> EdgeSet;
}
struct MyVisitorCycle : default_dfs_visitor {
MyVisitorCycle(EdgeSet &tree_edges, vector<vector<vertex_t> > &cycles1) :
tree_edges(tree_edges), cycles(cycles1) {}
void tree_edge(Edge e, const Graph& g) const {
std::cerr << "tree_edge " << e << std::endl;
tree_edges.insert(e);
}
void back_edge(Edge e, const Graph& g) const {
if (tree_edges.find(e) == tree_edges.end())
std::cerr << "back_edge " << e << std::endl;
/// I added this part
vertex_t s = vertex (0,g);
std::vector <vertex_t> p(num_vertices (g));
depth_first_search (g, s, visitor (boost::record_predecessors (&p[0],
on_tree_edge())));/// here has problem
p.push_back (target (e,g)); /// close the cycle
cycles.push_back (p);
}
private:
EdgeSet& tree_edges;
vector<vector <vertex_t> > &cycles;
};
int main() {
Graph g;
add_edge(0, 1, g);
add_edge(1, 2, g);
add_edge(2, 3, g);
add_edge(3, 0, g);
add_edge(1, 4, g);
add_edge(4, 5, g);
add_edge(5, 6, g);
add_edge(6, 3, g);
add_edge(2, 5, g);
std::set<Edge> tree_edges;
vector<vector <vertex_t> > cycles;
MyVisitorCycle vis(tree_edges, cycles);
depth_first_search(g, visitor(vis));
}