-
Notifications
You must be signed in to change notification settings - Fork 0
/
Detect cycle in an undirected graph.cpp
78 lines (64 loc) · 1.29 KB
/
Detect cycle in an undirected 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
1.USING BFS
bool isCyclicConn(vector<int> adj[],int s,int V,vector<bool>& vis)
{
vector<int> parent(V,-1);
queue<int> q;
q.push(s);
vis[s]=true;
while(!q.empty())
{
int u=q.front();
q.pop();
for(auto v:adj[u])
{
if(!vis[v])
{
vis[v]=true;
q.push(v);
parent[v]=u;
}
else if(parent[u]!=v)
return true;
}
}
return false;
}
bool isCyclic(vector<int> adj[], int V)
{
vector<bool> vis(V,false);
for(int i=0;i<V;i++)
{
if(!vis[i]&&isCyclicConn(adj,i,V,vis))
return true;
}
return false;
}
2.USING DFS
bool isCyclicConn(vector<int> adj[],vector<bool>& vis,int s,int parent)
{
vis[s]=true;
for(auto v:adj[s])
{
if(!vis[v])
{
if(isCyclicConn(adj,vis,v,s))
return true;
}
else if(vis[v]==true && v!=parent)
return true;
}
return false;
}
bool isCyclic(vector<int> adj[],int V)
{
vector<bool> vis(V,false);
for(int i=0;i<V;i++)
{
if(!vis[i])
{
if(isCyclicConn(adj,vis,i,-1))
return true;
}
}
return false;
}