-
Notifications
You must be signed in to change notification settings - Fork 0
/
Cycle_Detection_Undirected_DFS.cpp
68 lines (58 loc) · 1.21 KB
/
Cycle_Detection_Undirected_DFS.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
// Implementation of Cycle detection of Undirected graph using DFS
//
// Running Time Complexity : O(V+E)
#include<bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
#define int long long
#define pii pair<int, int>
const int N = 100005;
bool vis[N];
int V, E;
vector<int> adj[N];
bool isCyclic(int u, int parent)
{
vis[u] = true;
int i, v;
bool flag = false;
for(i = 0 ; i < adj[u].size() ; i++)
{
v = adj[u][i];
if(!vis[v])
flag |= isCyclic(v, u);
else
{
if(v == parent)
continue;
else
return true;
}
}
return flag;
}
int32_t main()
{
int x, y, i;
bool cycle = true;
memset(vis, false, sizeof(vis));
cout << "Enter the no of Nodes";
cin >> V;
cout << "Enter the no of Edges";
cin >> E;
for(i = 0 ; i < E ; i++)
{
cin >> x >> y;
adj[x].push_back(y);
adj[y].push_back(x);
}
for(i = 0 ; i < V ; i++)
{
if(vis[i] == 0)
cycle &= isCyclic(i, -1);
}
if(cycle)
cout << "The Graph is cyclic" << endl;
else
cout << "The Graph is not cyclic" << endl;
return 0;
}