minh_tran_782

Bai2_Graph_HCMUT

Nov 14th, 2021 (edited)
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.38 KB | None | 0 0
  1. #include<iostream>
  2. #include <list>
  3. using namespace std;
  4.  
  5. class DirectedGraph
  6. {
  7.     int V;
  8.     list<int> *adj;
  9.     bool isCyclicUtil(int v, bool visited[], bool *rs);
  10. public:
  11.     DirectedGraph(){
  12.         V = 0;
  13.         adj = NULL;
  14.     }
  15.     DirectedGraph(int V)
  16.     {
  17.         this->V = V;
  18.         adj = new list<int>[V];
  19.     }
  20.     void addEdge(int v, int w)
  21.     {
  22.         adj[v].push_back(w);
  23.     }
  24.     bool isCyclic()
  25.     {
  26.             // Mark all the vertices as not visited and not part of recursion
  27.     // stack
  28.     bool *visited = new bool[V];
  29.     bool *recStack = new bool[V];
  30.     for(int i = 0; i < V; i++)
  31.     {
  32.         visited[i] = false;
  33.         recStack[i] = false;
  34.     }
  35.  
  36.     // Call the recursive helper function to detect cycle in different
  37.     // DFS trees
  38.     for(int i = 0; i < V; i++)
  39.         if (isCyclicUtil(i, visited, recStack))
  40.             return true;
  41.  
  42.     return false;
  43.     }
  44. };
  45.       bool  DirectedGraph::isCyclicUtil(int v, bool visited[], bool *recStack)
  46. {
  47.     if(visited[v] == false)
  48.     {
  49.         // Mark the current node as visited and part of recursion stack
  50.         visited[v] = true;
  51.         recStack[v] = true;
  52.  
  53.         // Recur for all the vertices adjacent to this vertex
  54.         list<int>::iterator i;
  55.         for(i = adj[v].begin(); i != adj[v].end(); ++i)
  56.         {
  57.             if ( !visited[*i] && isCyclicUtil(*i, visited, recStack) )
  58.                 return true;
  59.             else if (recStack[*i])
  60.                 return true;
  61.         }
  62.  
  63.     }
  64.     recStack[v] = false; // remove the vertex from recursion stack
  65.     return false;
  66. }
Add Comment
Please, Sign In to add comment