forked from client69/Open
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcycle_detect.cpp
More file actions
148 lines (117 loc) · 2.25 KB
/
Copy pathcycle_detect.cpp
File metadata and controls
148 lines (117 loc) · 2.25 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
#include<bits/stdc++.h>
using namespace std;
class Graph
{
int V;
vector< vector<int> >adj;
bool isCyclicUtil(int v,vector<bool> &visited,int parent);
public:
Graph(int V);
void addEdge(int v,int w);
bool isCyclic();
};
Graph::Graph(int V)
{
this->V=V;
adj=vector< vector<int> >(V);
}
void Graph::addEdge(int v,int w)
{
adj[v].push_back(w);
adj[w].push_back(v);
}
bool Graph::isCyclicUtil(int v,vector<bool> &visited,int parent)
{
visited[v]=true;
vector<int>::iterator i;
for(i=adj[v].begin();i!=adj[v].end();++i)
{
if(!visited[*i])
{
if(isCyclicUtil(*i,visited,v)) return true;
}
else if(*i!=parent) return true;
}
return false;
}
bool Graph::isCyclic()
{
vector<bool> visited(V);
for(int i=0;i<V;++i)
{
visited[i]=false;
}
for(int u=0;u<V;++u)
{
if(!visited[u])
{
if(isCyclicUtil(u,visited,-1))
{
return true;
}
}
}
return false;
}
int main()
{
int n,e,a,b;
cout<<"Enter number of nodes:"<<endl;
cin>>n;
cout<<"Enter number of edges:"<<endl;
cin>>e;
Graph g(n);
cout<<"Enter edges:"<<endl;
for(int i=0;i<e;++i){
cin >> a >> b;
g.addEdge(a,b);
}
g.isCyclic()? cout << "Cycle detected!\n":
cout << "No cycle detected!\n";
return 0;
}
/*
------ OUTPUT 1: ------
Enter number of nodes:
5
Enter number of edges:
5
Enter edges:
0 1
1 2
2 3
2 4
3 4
Cycle detected!
Nodes: 0,1,2,3,4
0
/
1----2
/ \
3---4
Edges: {0,1}, {1,2}, {2,3}, {2,4}, {3,4}.
Cycle: 2
/ \
3---4
Cycle detected.
----- OUTPUT 2: -----
Enter number of nodes:
5
Enter number of edges:
4
Enter edges:
0 1
1 2
2 3
2 4
No cycle detected!
Nodes: 0,1,2,3,4
0----1
|
|
2
/ \
3 4
Edges: {0,1}, {1,2}, {2,3}, {3,4}.
Graph doesn't contain a cycle.
*/