如何使用Boost.Graph从特定节点遍历图分支?

时间:2015-06-04 08:47:45

标签: c++ boost graph

非常感谢您的帮助 我有树结构,并希望打印节点按照层次结构的顺序发生。

例如,我想遍历所有N1的孩子:

[N0, N1[N2, N3, N4[N5], N6]

我希望得到

N1 N2 N3 N4 N5

但我使用此代码段收到了不同的内容:

    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 _tmain(int argc, _TCHAR* argv[])
{    
     MyGraph g;

        boost::add_edge(0, 1, g);
        boost::add_edge(0, 2, g);
        boost::add_edge(0, 3, g);
        boost::add_edge(2, 4, g);

        MyVisitor vis;

        //2 - N2 node 
        boost::depth_first_search(g,  boost::visitor(vis).root_vertex(2) );
        return 0;

}

输出是:

2
0
1
3
4

但我期待(2和所有孩子)

2
4

请帮忙。

谢谢。

1 个答案:

答案 0 :(得分:1)

您的图表是无向的,这意味着也会使用备份(0,2)。

尝试将undirectedS更改为directedS

为避免报告从其他根发现的顶点,您可以调整访问者以检测第一个rootdone的时间:

<强> Live On Coliru

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graphviz.hpp>
#include <boost/graph/depth_first_search.hpp>
#include <boost/graph/visitors.hpp>
#include <iterator>

using Graph = boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS>;
using VertexPair = std::pair<Graph::vertex_descriptor, Graph::vertex_descriptor>;

struct Visitor : boost::default_dfs_visitor {
    using V = Graph::vertex_descriptor;

    void discover_vertex(V v, const Graph& /*g*/) {
        if (!root) {
            root = v;
        }
        if (!done) std::cerr << v << "\n";
    }

    void finish_vertex(V v, const Graph& /*g*/) {
        done |= (root == v);
    }
  private:
    bool done = false;
    boost::optional<V> root;
};

int main() {
    // [N0, N1[N2, N3, N4[N5], N6] :
    // VertexPair const data[] { {1, 2}, {1, 3}, {1, 4}, {4, 5}, };
    VertexPair const data[] { {0, 1}, {0, 2}, {0, 3}, {2, 4}, };
    Graph g(std::begin(data), std::end(data), 7);

    boost::depth_first_search(g, boost::visitor(Visitor()).root_vertex(2));
    //boost::write_graphviz(std::cout, g);
}

打印

2
4

<强>更新

如果为了提高效率,您希望避免遍历树的其余部分,则可以使用depht_first_visitTerminatorFunc可以使用// in Visitor: // the TerminatorFunc bool operator()(V, Graph const&) const { return done; } // later: Visitor vis_termfuc; // combines visitor and terminator functions std::vector<boost::default_color_type> colormap(num_vertices(g)); boost::depth_first_visit(g, 2, vis_termfuc, colormap.data(), vis_termfuc); 。在这里,我将其添加到同一位访客:

<强> Live On Coliru

_www
相关问题