简体   繁体   中英

Find all topological sorts in a DAG using BGL (Boost graph library)

How can use the Boost Graph Library to find all the topological sorts of a given DAG G ?

I have found some theoretical references explaining that is possible, there's also this code where there's an implementation. But I don't actually want to start from scratch, and I want to use BGL to compute them.

One strategy would be to get all vertices without predecessors (no directed edges to it). And multiplying vectors based on vertices without predecessors. If you have a C++ to do it please share.

The code to get depth_first topological sort:

Given a DAG graph with vertex type vertex_t :

deque<vertex_t> topologicalSorted;

//perform topological sort
if (topologicalSort(graph, topologicalSorted)) {
    cout << "The graph is directed acyclic!" << endl;
    cout << "Topological order: ";
    for (int i = 0; i < topologicalSorted.size(); i++) {
        cout << graph[topologicalSorted.at(i)].label << " ";
    }
    cout << endl;
} 


bool topologicalSort()
{
    try
    {
        boost::topological_sort(graph, front_inserter(topologicalSorted));
    }
    catch (boost::not_a_dag)
    {
        cout << "not a dag\n";
        return false;
    }
    cout << "top sort OK\n";

    return true;
} 

Without custom vertex:

deque<int> topologicalSorted;

if (topologicalSort()) {
        // Print the results.
        for (int i = 0; i < topologicalSorted.size(); i++) {
            cout << topologicalSorted.at(i) << ",";
        }
        cout << endl;
    } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM