-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdetect_Cycle _Using_Disjoint_Set_Union_Find_Algorithm.cpp
More file actions
91 lines (80 loc) · 2.04 KB
/
Copy pathdetect_Cycle _Using_Disjoint_Set_Union_Find_Algorithm.cpp
File metadata and controls
91 lines (80 loc) · 2.04 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <iostream>
#include <vector>
#include "set"
#include "unordered_map"
using namespace std;
struct Edge{
int source,destination;
};
class Graph{
vector<vector<int>> adjList;
int V;
public:
Graph(vector<Edge> edges,int V){
this->V = V;
adjList.resize(V);
for(auto i: edges){
adjList[i.source].push_back(i.destination);
//adjList[i.destination].push_back(i.source);
}
}
void DFS(int s,vector<bool> &discovered);
bool findCycle();
void printGraph();
};
class DisjointSet{
unordered_map <int ,int> parent;
public:
void makeSet(int V){
for(int i = 1;i<= V;i++) parent[i] = i;
}
int Find(int k ){
if(parent[k] == k) return k ;
return Find(parent[k]);
}
void Union(int a, int b){
parent[Find(a)] = Find(b);
}
void printSets(vector <int> universe){
for(auto i:universe) cout <<Find(i) <<" "; cout <<"\n";
}
};
void Graph ::printGraph() {
for (int i = 1; i < V; i++)
{
cout << i << " -- ";
for (int v : adjList[i])
cout <<"->"<< v << " ";
cout << endl;
}
}
void Graph ::DFS(int s, vector<bool> &discovered) {
discovered[s] = true;
for(auto i : adjList[s]){
if(!discovered[i]) DFS(i,discovered);
}
}
bool Graph :: findCycle(){
DisjointSet ds;
ds.makeSet(V);
for(int i =1;i<= V;i++){
for(auto j : adjList[i]){
if(ds.Find(i) == ds.Find(j)) return true;
else ds.Union(i,j);
}
}
return false;
}
int main(){
vector<Edge> edges =
{ {1, 2}, {1, 7}, {1, 8}, {2, 3}, {2, 6}, {3, 4},
{3, 5}, {8, 9}, {8, 12}, {9, 10}, {9, 11}, {11, 12}
};
set <int > setsize;
for(auto i : edges){ setsize.insert(i.source);setsize.insert(i.destination);}
int V = setsize.size();
Graph graph(edges, V + 1);
// graph.printGraph();
if(graph.findCycle()) cout<<"Cycle Exists";
else cout<<"Cycle does not exists";
}