-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathCycleDetctionDirected.cpp
More file actions
71 lines (66 loc) · 1.02 KB
/
CycleDetctionDirected.cpp
File metadata and controls
71 lines (66 loc) · 1.02 KB
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
65
66
67
68
69
70
71
#include<iostream>
#include<stack>
#include<utility>
#include<vector>
using namespace std;
#define pb push_back
#define mp make_pair
#define MAXN 150
vector<int> G[MAXN];
bool dfs(int node,vector<bool> &recstack,vector<bool> &visited)
{
visited[node] = true;
recstack[node] = true;
vector<int>::iterator it;
for(it = G[node].begin(); it != G[node].end(); it++)
{
if(!visited[*it]&&dfs(*it,recstack,visited))
{
return true;
}
if(recstack[*it])
{
return true;
}
}
recstack[node]=false;
return false;
}
bool CycleDetectionDirected(int M)
{
vector<bool> visited(M, false);
vector<bool> recstack(M, false);
for(int i = 0; i < M; i++)
{
if(dfs(i, recstack, visited))
{
return true;
}
}
return false;
}
int main()
{
int N, M;
cin >> N >> M;
for(int i = 0; i < MAXN; i++)
{
G[i].clear();
}
int U, V;
for(int i = 0; i < N; i++)
{
cin >> U >> V;
G[U].pb(V);
}
//cout<<"wow"<<endl;
if(CycleDetectionDirected(M))
{
cout<<"Cycle Detected\n";
}
else
{
cout<<"No Cycle\n";
}
return 0;
}