ronith
9/28/2018 - 12:55 PM

All Topological Sorts of a Directed Acyclic Graph

#include <iostream>
using namespace std;

class graph {
    int v;
    int **adj;
    int *indegree;
public:
    graph (int v) {
        this->v= v;
        adj= new int* [v];
        for (int i=0; i<v; i++)
            adj[i]= new int [v];
        for (int i=0; i<v; i++)
            for (int j=0; j<v; j++)
                adj[i][j]==0;
        indegree= new int [v];
        for (int i=0; i<v; i++)
            indegree[i]= 0;
    }
    void addEdge (int u, int w) {
        adj[u][w]=1;
        indegree[w]++;
    }
    void AllTS();
    void TSUtil (bool [], int [], int &);
};
void graph::TSUtil(bool visited[], int st[], int &top) {
    bool flag= true;

    for (int i=0;i<v;i++) {
        if (indegree[i]==0 && !visited[i]) {
            for (int j=0; j<v; j++)
                if (adj[i][j]==1)
                    indegree[j]--;

            st[top++]=i;
            visited[i]= 1;
            TSUtil(visited, st, top);

            visited[i]=0;
            top--;
            for (int j=0; j<v; j++)
                if (adj[i][j]==1)
                    indegree[j]++;
            flag=false;
        }
    }
    if (flag) {
        for (int i=0;i<top;i++)
            cout<< st[i]<< " ";
        cout<< "\n";
    }
}
void graph::AllTS() {
    int st[v], top=0;
    bool visited[v]= {0};
    TSUtil(visited, st, top);
}
int main() {
    graph g(6);
    g.addEdge(5, 2);
    g.addEdge(5, 0);
    g.addEdge(4, 0);
    g.addEdge(4, 1);
    g.addEdge(2, 3);
    g.addEdge(3, 1);

    g.AllTS();
}