Advertisement
kartikkukreja

Topological Sorting

Jun 21st, 2013
301
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.11 KB | None | 0 0
  1. #include <cstdio>
  2. #include <vector>
  3. #include <list>
  4. #include <cstring>
  5.  
  6. using namespace std;
  7.  
  8. // Class to represent a Digraph, with vertices labeled
  9. // from 0 to V-1, where V is the number of vertices
  10. class Graph {
  11. private:
  12.     int V;
  13.     vector <int>* adjList;
  14.     bool* explored;
  15.     list <int> topologicalOrder;
  16.  
  17.     void dfsUtil(int u) {
  18.         explored[u] = true;
  19.         for (vector <int>::iterator v = adjList[u].begin(); v != adjList[u].end(); v++)
  20.             if (!explored[*v])
  21.                 dfsUtil(*v);
  22.         topologicalOrder.push_front(u);
  23.     }
  24.  
  25.     void dfs()    {
  26.         for (int u = 0; u < V; u++)
  27.             if (!explored[u])
  28.                 dfsUtil(u);
  29.     }
  30.  
  31. public:
  32.  
  33.     // create an empty Digraph having V vertices
  34.     Graph(int V) {
  35.         this->V = V;
  36.         adjList = new vector <int>[V];
  37.         explored = new bool[V];
  38.         memset(explored, false, V * sizeof(bool));
  39.     }
  40.  
  41.     ~Graph()    {
  42.         delete [] adjList;
  43.         delete [] explored;
  44.     }
  45.  
  46.     // add a directed edge u -> v to the digraph
  47.     // returns false if either u or v is less than 0 or greater than equal to V
  48.     // returns true if the edge was added to the digraph
  49.     bool addEdge(int u, int v)  {
  50.         if (u < 0 || u >= V) return false;
  51.         if (v < 0 || v >= V) return false;
  52.         adjList[u].push_back(v);
  53.         return true;
  54.     }
  55.  
  56.     list <int> getTopologicalOrder()    {
  57.         if (topologicalOrder.empty())
  58.             dfs();
  59.  
  60.         return topologicalOrder;
  61.     }
  62.  
  63.     void printTopologicalOrder()    {
  64.         if (topologicalOrder.empty())
  65.             dfs();
  66.  
  67.         printf("Topological Order :");
  68.         for (list<int>::iterator it = topologicalOrder.begin(); it != topologicalOrder.end(); it++)
  69.             printf(" %d", *it);
  70.         printf("\n");
  71.     }
  72.  
  73. };
  74.  
  75. int main() {
  76.     Graph G(8);
  77.  
  78.     G.addEdge(2, 0);
  79.     G.addEdge(1, 2);
  80.     G.addEdge(2, 3);
  81.     G.addEdge(2, 5);
  82.     G.addEdge(6, 2);
  83.     G.addEdge(7, 5);
  84.     G.addEdge(4, 7);
  85.     G.addEdge(6, 7);
  86.     G.addEdge(4, 3);
  87.  
  88.     G.printTopologicalOrder();
  89.  
  90.     return 0;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement