fork(2) download
  1. #include<cstdio>
  2. #include<list>
  3. #include<queue>
  4.  
  5. using namespace std;
  6.  
  7. int V;
  8. list<int>* point;
  9.  
  10.  
  11.  
  12. void Graph_Make(int V)
  13. {
  14. point=new list<int>[V];
  15. }
  16.  
  17.  
  18. void Edge_Create(int u,int v)
  19. {
  20. point[u].push_back(v);
  21. }
  22.  
  23. void Show_Graph()
  24. {
  25. int i;
  26. for(i=0;i<V;i++)
  27. {
  28. printf("\n");
  29. printf("%d :",i);
  30. for(auto it=point[i].begin();it!=point[i].end();it++)
  31. printf("%d ",*it);
  32. }
  33. }
  34.  
  35. bool Check_for_cycle(int v,bool array1[],bool stack1[])
  36. {
  37. array1[v]=true;
  38. stack1[v]=true;
  39.  
  40. for(auto it=point[v].begin();it!=point[v].end();it++)
  41. {
  42. if(!array1[*it]&&Check_for_cycle(*it,array1,stack1))
  43. return(true);
  44. else if(stack1[*it])
  45. return(true);
  46. }
  47. stack1[v]=false;
  48. return(false);
  49. }
  50.  
  51.  
  52. bool is_Cycle()
  53. {
  54. bool array1[V],stack1[V];
  55. int i;
  56. for(i=0;i<V;i++)
  57. {
  58. array1[i]=false;
  59. stack1[i]=false;
  60. }
  61. for(i=0;i<V;i++)
  62. {
  63. if(array1[i]==false)
  64. {
  65. if(Check_for_cycle(i,array1,stack1))
  66. return true;
  67. }
  68. }
  69. return false;
  70. }
  71.  
  72.  
  73.  
  74. int main(void)
  75. {
  76. int s;
  77. bool check;
  78. printf("\n Enter the vertices in a graph");
  79. scanf("%d",&V);
  80. Graph_Make(V);
  81. Edge_Create(1,0);
  82. Edge_Create(0,2);
  83. Edge_Create(3,1);
  84. Edge_Create(2,3);
  85. Show_Graph();
  86. check=is_Cycle();
  87. if(check==true)
  88. printf("\n Graph has a cycle");
  89. else
  90. printf("\n Graph doesn't have any cycle");
  91. return(0);
  92. }
  93.  
Success #stdin #stdout 0s 3476KB
stdin
4
stdout
 Enter the vertices in a graph
0 :2 
1 :0 
2 :3 
3 :1 
 Graph has a cycle