c_cpp [graph] [dfs]拓扑排序图

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp [graph] [dfs]拓扑排序图相关的知识,希望对你有一定的参考价值。

#include <iostream>
#include <stack>
#include <list>
using namespace std;

#define WHITE 0 // never visited
#define GRAY 1  // itself is visited, but its neighbors are still under visit
#define BLACK 2 // both itself and all its neighbors are visited

class graph {
    int numV;
    list<int> *adj;
public:
    graph(int n) {
        numV = n;
        adj = new list<int>[n];
    }
    
    void add_edge(int v, int w) {
        adj[v].push_back(w);
    }
    
    void dfs(int v, int *visited, stack<int>& stk) {
        visited[v] = GRAY; 
        for(auto w : adj[v]) {
            if(visited[w] == GRAY) {  // find a loop
                cout << "Loop found! No topological order exist! \n";
                break;
            }
            if(visited[w] == WHITE) 
                dfs(w, visited, stk);
            // POS1
        }
        visited[v] = BLACK; // should be here not POS1
        stk.push(v);        // should be here not POS1
    }
    
    void topological_sort() {
        int *visited = new int[numV];
        for(int i=0; i<numV; i++) visited[i] = WHITE;
        stack<int> stk;
        for(int i=0; i<numV; i++) {
            if(visited[i] == 0) 
                dfs(i, visited, stk);
        }
        while(stk.empty() == false) {
            cout << stk.top() << " ";
            stk.pop();
        }
    }
};

int main()
{
    graph *g = new graph(4);
    g->add_edge(0,1);
    g->add_edge(1,2);
    g->add_edge(2,0);
    g->add_edge(1,3);
    g->topological_sort();
}

以上是关于c_cpp [graph] [dfs]拓扑排序图的主要内容,如果未能解决你的问题,请参考以下文章

CodeForces915 D. Almost Acyclic Graph 拓扑排序找环

图论(graph)相关算法总结

Python中的拓扑排序算法(DFS)实现

使用 DFS 算法对有向图和无向图进行拓扑排序

拓扑排序(Topological Sort)

5.6 拓扑排序