在boost中查找有向图的所有循环

Find all cycles of directed graph in boost

谁能告诉我如何使用 boost 图形库查找有向图的所有循环?

Google turns up the - otherwise undocumented - tiernan_all_cycles. There is an example 不过

该示例预设了 less-than-optimal 个图形模型。根据问题 #182,你应该真的能够满足 adjacency-list 的缺失概念要求(前提是它有一个正确的顶点索引):

using Graph = boost::adjacency_list<boost::vecS, boost::vecS, boost::/*un*/directedS>;

// see https://github.com/boostorg/graph/issues/182
namespace boost { void renumber_vertex_indices(Graph const&) {} }

这是一个现代化的例子:

Live On Compiler Explorer

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/tiernan_all_cycles.hpp>
#include <iostream>

using Graph = boost::adjacency_list<boost::vecS, boost::vecS, boost::/*un*/directedS>;

// see https://github.com/boostorg/graph/issues/182
namespace boost { void renumber_vertex_indices(Graph const&) {} }

struct Vis {
    void cycle(auto const& path, Graph const& g) const {
        auto indices = get(boost::vertex_index, g);
        for (auto v : path)
            std::cout << "ABCDEFGHIJKL"[get(indices, v)] << " ";
        std::cout << "\n";
    };
};

int main()
{
    enum { A, B, C, D, E, F, G, H, I, J, K, L, NUM };
    Graph g(NUM);
    // Graph from https://commons.wikimedia.org/wiki/File:Graph_with_Chordless_and_Chorded_Cycles.svg
    for (auto [s, t] : { std::pair //
            {A, B}, {B, C}, {C, D}, {D, E}, {E, F}, {F, A},
            {G, H}, {H, I}, {I, J}, {J, K}, {K, L}, {L, G},
            {C, L}, {D, K}, {B, G}, {C, G}, {I, K}
         }) //
        add_edge(s, t, g);

    tiernan_all_cycles(g, Vis{});
}

版画

A B C D E F 
G H I J K L 
G H I K L