Recording predecessors in a DFS search in an undirected graph

后端 未结 1 1174
你的背包
你的背包 2021-01-28 14:48

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 eac

相关标签:
1条回答
  • 2021-01-28 15:17

    Here's a quick post, I'll come back with some notes later

    Live On Coliru

    #include <iostream>
    #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 MyVisitor : default_dfs_visitor {
        MyVisitor(EdgeSet& tree_edges) : tree_edges(tree_edges) {}
    
        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;
        }
    
      private: 
        EdgeSet& tree_edges;
    };
    
    int main() {
        Graph g;
        add_edge(0, 1, g);
        add_edge(0, 2, g);
    
        std::set<Edge> tree_edges;
        MyVisitor vis(tree_edges);
    
    
        std::vector<Graph::vertex_descriptor> pred(num_vertices(g), Graph::null_vertex());
    
        depth_first_search(g, visitor(boost::make_dfs_visitor(
                boost::record_predecessors(pred.data(), boost::on_back_edge{})
            )));
    
        for (auto v : make_iterator_range(vertices(g))) {
            std::cout << "Predecessor for " << v << " is " << pred.at(v) << "\n";
        }
    }
    

    Prints

    Predecessor for 0 is 2
    Predecessor for 1 is 18446744073709551615
    Predecessor for 2 is 18446744073709551615
    
    0 讨论(0)
提交回复
热议问题