Advertisement
minh_tran_782

Bai4_Topo_sort

Nov 14th, 2021
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.25 KB | None | 0 0
  1. class Graph {
  2.  
  3.     int V;
  4.     Adjacency* adj;
  5.  
  6. public:
  7.     Graph(int V){
  8.         this->V = V;
  9.         adj = new Adjacency[V];
  10.     }
  11.     void addEdge(int v, int w){
  12.         adj[v].push(w);
  13.     }
  14.    
  15.     //Heling functions
  16.    void  topologicalSortUtil(int v, bool visited[],
  17.                                 list<int>& Stack)
  18. {
  19.     // Mark the current node as visited.
  20.     visited[v] = true;
  21.  
  22.     // Recur for all the vertices
  23.     // adjacent to this vertex
  24.     int size = adj[v].getSize();
  25.     for (int i = 0;  i  < size; ++i)
  26.         {
  27.             int ele = adj[v].getElement(i);
  28.             if (!visited[ele])
  29.             topologicalSortUtil(ele, visited, Stack);
  30.         }
  31.  
  32.     // Push current vertex to stack
  33.     // which stores result
  34.     Stack.push_front(v);
  35. }
  36.     void topologicalSort(){
  37.        list<int> Stack;
  38.  
  39.     // Mark all the vertices as not visited
  40.     bool* visited = new bool[V];
  41.     for (int i = 0; i < V; i++)
  42.         visited[i] = false;
  43.  
  44.     // Call the recursive helper function
  45.     // to store Topological
  46.     // Sort starting from all
  47.     // vertices one by one
  48.     for (int i = 0; i < V; i++)
  49.         if (visited[i] == false)
  50.             topologicalSortUtil(i, visited, Stack);
  51.  
  52.     // Print contents of stack
  53.     while (Stack.empty() == false) {
  54.         cout << Stack.front() << " ";
  55.         Stack.pop_front();
  56.     }
  57.     }
  58. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement