File tree 1 file changed +76
-0
lines changed
1 file changed +76
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < iostream>
2
+ #include < list>
3
+ #include < cstring>
4
+ using namespace std ;
5
+
6
+ class Graph {
7
+ int V;
8
+ list<int > *adj;
9
+
10
+ bool isCyclicHelper (int s,bool *visited,bool *RStack){
11
+ if (visited[s]==false ){
12
+ visited[s] = true ;
13
+ rStack[s] = true ;
14
+
15
+ for (auto it=adj[s].begin ();it!=adj[s].end ();it++){
16
+ if (!visited[*it]&&isCyclicHelper (*it,visited,rStack)){
17
+ return true ;
18
+ }
19
+ else if (rStack[*it]){
20
+ return true ;
21
+ }
22
+ }
23
+
24
+ }
25
+ RStack[s]=false ;
26
+ return false ;
27
+ }
28
+
29
+
30
+ public:
31
+ Graph (int V){
32
+ this ->V = V;
33
+ adj = new list<int >[V];
34
+ }
35
+
36
+ void addEdge (int u,int v){
37
+ adj[u].push_back (v);
38
+
39
+ }
40
+
41
+ bool isCyclic (){
42
+ bool *visited = new bool [V];
43
+ bool *rStack = new bool [V];
44
+
45
+ memset (visited,false ,sizeof (false ));
46
+ memset (rStack,false ,sizeof (false ));
47
+
48
+ // This works if there is a single DFS forest. Otherwise use a for loop.
49
+ if (isCyclicHelper (0 ,visited,rStack)){
50
+ return true ;
51
+ }
52
+ else {
53
+ return false ;
54
+ }
55
+ }
56
+
57
+ };
58
+
59
+ int main (){
60
+
61
+ Graph g (4 );
62
+ g.addEdge (0 , 1 );
63
+ g.addEdge (0 , 2 );
64
+ g.addEdge (1 , 2 );
65
+ g.addEdge (2 , 0 );
66
+ g.addEdge (2 , 3 );
67
+ g.addEdge (3 , 3 );
68
+
69
+ if (g.isCyclic ())
70
+ cout << " Graph contains cycle" ;
71
+ else
72
+ cout << " Graph doesn't contain cycle" ;
73
+ return 0 ;
74
+
75
+ return 0 ;
76
+ }
You can’t perform that action at this time.
0 commit comments