-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcycleInGraph.cpp
More file actions
64 lines (60 loc) · 1.49 KB
/
cycleInGraph.cpp
File metadata and controls
64 lines (60 loc) · 1.49 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
#include<stdio.h>
#include<stdlib.h>
#include<vector>
#include<stack>
#define N 10005
using namespace std;
stack <pair<int,int> > s;
int main()
{
vector <int> adj[N];//array of vectors
int vt[N];
int i,j,k,n,e,a,b;
scanf("%d%d",&n,&e);
for(i=0;i<e;i++)
{
scanf("%d%d",&a,&b);
adj[a].push_back(b);
adj[b].push_back(a);
}
for(i=0;i<N;i++)
vt[i]=0;
if(n!=(e+1))
{
printf("NO\n");
return 0;
}
else
{int i=1,parent,c=0,count=0;
parent=-1;
s.push(make_pair(i,parent));
while(!s.empty())
{
pair<int,int> kk=s.top();
s.pop();
int k=kk.first;
int p=kk.second;
vt[k]=1;//printf("parent=%d\n",p);
for(i=0;i<adj[k].size();i++)
{
int d=adj[k][i];
if(!vt[d])
{
p=k;s.push(make_pair(d,p));
}
else if(d!=p)//else if d is visited , then it must be the parent. If its not parent then there is a cycle
{c=1;
//printf("d=%d parent=%d\n",d,p);
break;}
}
if(c==1)
break;
count++;
}
if(c==1 ) printf("NO\n");
else if(count!=n) printf("NO\n");
else printf("YES\n");
}//else
return 0;
}
//Using two way adjacency list .Therefore using parent check