[graph] [dfs] topological sort a graph
#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();
}