forked from prashantkalokhe/Hactoberfest-2022-New
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDetect a cycle in Undirected Graph.cpp
68 lines (62 loc) · 1.36 KB
/
Detect a cycle in 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
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool checkForCycle(int s, int V, vector<int> adj[], vector<int> &visited)
{
queue<pair<int, int>> q;
visited[s] = true;
q.push({s, -1});
while (!q.empty())
{
int node = q.front().first;
int par = q.front().second;
q.pop();
for (auto it : adj[node])
{
if (!visited[it])
{
visited[it] = true;
q.push({it, node});
}
else if (par != it)
return true;
}
}
return false;
}
bool isCycle(int V, vector<int> adj[])
{
vector<int> vis(V - 1, 0);
for (int i = 1; i <= V; i++)
{
if (!vis[i])
{
if (checkForCycle(i, V, adj, vis))
return true;
}
}
}
};
void addEdge(vector<int> adj[],int u,int v)
{
adj[u].push_back(v);
adj[v].push_back(u);
}
int main()
{
vector<int> adj[5];
addEdge(adj,0,1);
addEdge(adj,0,2);
addEdge(adj,2,3);
addEdge(adj,1,3);
addEdge(adj,2,4);
Solution obj;
int num=obj.isCycle(5, adj);
if(num==1)
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
return 0;
}