-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathDetectCycleInUndirectedGraphUsingUnionFind.java
More file actions
107 lines (89 loc) · 2.42 KB
/
DetectCycleInUndirectedGraphUsingUnionFind.java
File metadata and controls
107 lines (89 loc) · 2.42 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
// http://www.geeksforgeeks.org/?p=26350
/*
Using union find subset algorithm
using path compression
using union by rank
Time Complexity - O(V log(V)) bcoz if there is a cycle it will return immediately after the Vth edge,
bcoz there can only be V-1 edges in a graph with no cycle
Union - O(log(n))
Find - O(log(n))
Space Complexity - O(V+E)
*/
class DetectCycleInUndirectedGraphUsingUnionFind {
public static void main(String[] args) {
Graph graph = new Graph(4);
graph.addEdge(0, 1);
graph.addEdge(1, 2);
graph.addEdge(2, 3);
graph.addEdge(0, 3);
String sol = graph.findCycle() ? "Yes" : "No";
System.out.println(sol);
}
}
class Graph {
int n;
ArrayList<LinkedList<Integer>> adjList;
int[] parent;
int[] rank;
Graph(int n) {
this.n = n;
adjList = new ArrayList<>();
for(int i = 0; i < n; i++) {
adjList.add(new LinkedList<>());
}
parent = new int[n];
rank = new int[n];
for(int i = 0; i < n; i++) {
parent[i] = i;
}
}
void addEdge(int x, int y) {
adjList.get(x).add(y);
}
boolean findCycle() {
for(int i = 0; i < n; i++) {
Iterator<Integer> iterator = adjList.get(i).iterator();
while(iterator.hasNext()) {
int x = iterator.next();
int parentI = find(i);
int parentX = find(x);
if(parentI != parentX) {
union(i, x);
} else {
return true;
}
}
}
return false;
}
// path compression
int find(int i) {
if(parent[i] == i) {
return i;
} else {
parent[i] = find(parent[i]);
return parent[i];
}
}
// union by rank
void union(int i, int j) {
int irep = find(i);
int jrep = find(j);
if(irep == jrep) {
return;
}
int irank = rank[irep];
int jrank = rank[jrep];
if(irank < jrank) {
this.parent[irep] = jrep;
} else if(jrank < irank) {
this.parent[jrep] = irep;
} else {
parent[irep] = jrep;
rank[jrep]++;
}
}
}