【问题标题】:How to create a C++ Boost undirected graph and traverse it in depth first search (DFS) order?如何创建 C++ Boost 无向图并以深度优先搜索 (DFS) 顺序遍历它?
【发布时间】:2010-09-06 01:27:30
【问题描述】:

如何创建 C++ Boost 无向图并以深度优先搜索 (DFS) 顺序对其进行遍历?

【问题讨论】:

    标签: c++ boost-graph


    【解决方案1】:
    // Boost DFS example on an undirected graph.
    // Create a sample graph, traverse its nodes
    // in DFS order and print out their values.
    
    #include <boost/graph/adjacency_list.hpp>
    #include <boost/graph/depth_first_search.hpp>
    #include <iostream>
    using namespace std;
    
    typedef boost::adjacency_list<boost::listS, boost::vecS, boost::undirectedS> MyGraph;
    typedef boost::graph_traits<MyGraph>::vertex_descriptor MyVertex;
    
    class MyVisitor : public boost::default_dfs_visitor
    {
    public:
      void discover_vertex(MyVertex v, const MyGraph& g) const
      {
        cerr << v << endl;
        return;
      }
    };
    
    int main()
    {
      MyGraph g;
      boost::add_edge(0, 1, g);
      boost::add_edge(0, 2, g);
      boost::add_edge(1, 2, g);
      boost::add_edge(1, 3, g);
    
      MyVisitor vis;
      boost::depth_first_search(g, boost::visitor(vis));
    
      return 0;
    }
    

    【讨论】:

    • 如果想把顶点1当作根怎么办?
    • boost::depth_first_search(g, vertex(1,g), boost::visitor(vis));
    猜你喜欢
    • 2019-08-10
    • 1970-01-01
    • 2016-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多