-
Notifications
You must be signed in to change notification settings - Fork 0
/
Detect cycle in an undirected graph(DFS).cpp
70 lines (64 loc) · 1.22 KB
/
Detect cycle in an undirected graph(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
69
70
#include <bits/stdc++.h>
using namespace std;
bool isCyclic(int node, int parent, const vector<vector < int>> &adjList, vector< bool > &visited)
{
visited[node] = true;
int neighbours = adjList[node].size();
for (int i = 0; i < neighbours; i++)
{
int neighbourNode = adjList[node][i];
if (!visited[neighbourNode])
{
if (isCyclic(neighbourNode, node, adjList, visited) == true)
{
return true;
}
}
else if (neighbourNode != parent)
{
return true;
}
}
return false;
}
void addEdge(vector<vector < int>> &adjList, int x, int y)
{
adjList[x].push_back(y);
adjList[y].push_back(x);
}
int main()
{
int n, m;
cout << "Enter number of nodes and edges: " << endl;
cin >> n >> m;
vector<bool> visited(n, false);
vector<vector < int>> adjList(n);
cout << "Enter edges: " << endl;
for (int i = 0; i < m; i++)
{
int u, v;
cin >> u >> v;
addEdge(adjList, u, v);
}
int flag = 0;
for (int i = 0; i < n; i++)
{
if (!visited[i])
{
if (isCyclic(i, -1, adjList, visited))
{
flag = 1;
break;
}
}
}
if (flag == 1)
{
cout << "Cycle found" << "\n";
}
else
{
cout << "Cycle not found" << "\n";
}
return 0;
}