-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Cycle_Detection_Directed_GRAPH.cpp
64 lines (54 loc) · 1.25 KB
/
Cycle_Detection_Directed_GRAPH.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//
// Created by rajat joshi on 29-05-2022.
//
#include<bits/stdc++.h>
using namespace std;
set<int>white;
set<int>gray;
set<int>black;
int flag=0;
void edge(vector<int>adj[],int u,int v)
{
adj[u].push_back(v);
}
void detectCycle(int u,vector<int>adj[])
{
white.erase(u);
gray.insert(u);
for(int i=0;i<adj[u].size();++i)
{
if(white.find(adj[u][i])!=white.end())
{
detectCycle(adj[u][i],adj);
}
if(gray.find(adj[u][i])!=gray.end())
{
flag=1;
}
}
black.insert(u);
gray.erase(u);
}
int main()
{
vector<int>adj[5];
edge(adj,0,2);
edge(adj,0,1);
edge(adj,1,3);
edge(adj,2,0);
edge(adj,3,3);
edge(adj,2,3);
edge(adj,2,4);
edge(adj,3,1);
edge(adj,4,2);
for(int i=0;i<5;++i)
{
white.insert(i);
}
detectCycle(0,adj);
if(flag==0)
{cout<<"Graph does not contain cycle"<<"\n";}
else
{cout<<"Graph contain cycle"<<"\n";}
return 0;
}