#include <iostream> #include <string> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/depth_first_search.hpp> // .dotファイルの出力用 #include <boost/graph/graphviz.hpp>
// Vertexクラス // Boost Graph Libraryでは node ではなく vertex という用語を使用 struct VertexProperty { std::string name; };
// グラフ定義 using Graph = boost::adjacency_list< boost::vecS, boost::vecS, boost::directedS, //単方向グラフ VertexProperty >;
using Vertex = boost::graph_traits<Graph>::vertex_descriptor;
// 深さ優先探索 class DFSVisitor : public boost::default_dfs_visitor { public: void discover_vertex(Vertex v, const Graph& g) const { std::cout << "Visited: " << g[v].name << std::endl; } };
int main() { Graph mygraph; // 頂点の追加 Vertex A = boost::add_vertex({ "A" }, mygraph); Vertex B = boost::add_vertex({ "B" }, mygraph); Vertex C = boost::add_vertex({ "C" }, mygraph); Vertex D = boost::add_vertex({ "D" }, mygraph); Vertex E = boost::add_vertex({ "E" }, mygraph); boost::add_edge(A, B, mygraph); // A→B boost::add_edge(A, C, mygraph); // A→C boost::add_edge(C, D, mygraph); // C→D boost::add_edge(C, E, mygraph); // C→E // 深さ優先探索 DFSVisitor vis; boost::depth_first_search(mygraph, boost::visitor(vis).root_vertex(A)); // DOTファイルに出力 std::ofstream ofs("graph.dot"); write_graphviz(ofs, mygraph, [&](std::ostream& out, const Vertex v) { out << "[label=\"" << mygraph[v].name << "\"]"; } ); // dot.exe -Tpng graph.dot -o a.png return 0; }