Skip to content

Commit b7ed199

Browse files
committed
🐶 Disjoint Set-Detect Cycle in a Graph
1 parent 46f1f50 commit b7ed199

File tree

1 file changed

+99
-0
lines changed

1 file changed

+99
-0
lines changed
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
2+
/**
3+
* A disjoint-set data structure is a data structure that
4+
* keeps track of a set of elements partitioned into a number of disjoint (non-overlapping) subsets.
5+
* A union-find algorithm is an algorithm that performs two useful operations on such a data structure:
6+
* Find: Determine which subset a particular element is in.
7+
* This can be used for determining if two elements are in the same subset.
8+
* Union: Join two subsets into a single subset.
9+
*
10+
* the implementation of union() and find() is naive and takes O(n) time in worst case.
11+
* These methods can be improved to O(Logn) using Union by Rank or Height.
12+
*/
13+
14+
import java.util.*;
15+
import java.io.*;
16+
17+
class DetectCycleDisjointSet {
18+
19+
int V, E;
20+
Edge edge[];
21+
22+
class Edge {
23+
int src, dest;
24+
};
25+
26+
DetectCycleDisjointSet(int v, int e) {
27+
V = v;
28+
E = e;
29+
edge = new Edge[E];
30+
for (int i = 0; i < e; ++i)
31+
edge[i] = new Edge();
32+
}
33+
34+
static int find(int parent[], int index) {
35+
36+
if (parent[index] == -1)
37+
return index;
38+
return find(parent, parent[index]);
39+
}
40+
41+
static void Union(int parent[], int x, int y) {
42+
int xSet = find(parent, x);
43+
int ySet = find(parent, y);
44+
parent[xSet] = ySet;
45+
}
46+
47+
static boolean isCycle(DetectCycleDisjointSet graph) {
48+
49+
int parent[] = new int[graph.V];
50+
51+
Arrays.fill(parent, -1);
52+
53+
for (int i = 0; i < graph.E; i++) {
54+
55+
int srcSet = find(parent, graph.edge[i].src);
56+
int destSet = find(parent, graph.edge[i].dest);
57+
58+
if (srcSet == destSet)
59+
return true;
60+
61+
Union(parent, srcSet, destSet);
62+
}
63+
64+
return false;
65+
}
66+
67+
public static void main(String[] args) {
68+
69+
int V = 5, E = 5;
70+
71+
DetectCycleDisjointSet graph = new DetectCycleDisjointSet(V, E);
72+
73+
74+
/**
75+
* 0
76+
* / \
77+
* 1 2
78+
* / \
79+
* 3 - 4
80+
*/
81+
82+
graph.edge[0].src = 0;
83+
graph.edge[0].dest = 1;
84+
85+
graph.edge[1].src = 0;
86+
graph.edge[1].dest = 2;
87+
88+
graph.edge[2].src = 1;
89+
graph.edge[2].dest = 3;
90+
91+
graph.edge[3].src = 1;
92+
graph.edge[3].dest = 4;
93+
94+
graph.edge[4].src = 3;
95+
graph.edge[4].dest = 4;
96+
97+
System.out.println("Graph contains cycle: " + isCycle(graph));
98+
}
99+
}

0 commit comments

Comments
 (0)