Skip to content

Commit 0174577

Browse files
Merge pull request #148 from nandubhai/master
Disjoint Set
2 parents 6d5091d + 57227c0 commit 0174577

File tree

1 file changed

+98
-0
lines changed

1 file changed

+98
-0
lines changed

Diff for: DisjointSet.java

+98
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
// Java Program for union-find algorithm to detect cycle in a graph
2+
import java.util.*;
3+
import java.lang.*;
4+
import java.io.*;
5+
6+
class Graph
7+
{
8+
int V, E; // V-> no. of vertices & E->no.of edges
9+
Edge edge[]; // /collection of all edges
10+
11+
class Edge
12+
{
13+
int src, dest;
14+
};
15+
16+
// Creates a graph with V vertices and E edges
17+
Graph(int v,int e)
18+
{
19+
V = v;
20+
E = e;
21+
edge = new Edge[E];
22+
for (int i=0; i<e; ++i)
23+
edge[i] = new Edge();
24+
}
25+
26+
// A utility function to find the subset of an element i
27+
int find(int parent[], int i)
28+
{
29+
if (parent[i] == -1)
30+
return i;
31+
return find(parent, parent[i]);
32+
}
33+
34+
// A utility function to do union of two subsets
35+
void Union(int parent[], int x, int y)
36+
{
37+
int xset = find(parent, x);
38+
int yset = find(parent, y);
39+
parent[xset] = yset;
40+
}
41+
42+
43+
// The main function to check whether a given graph
44+
// contains cycle or not
45+
int isCycle( Graph graph)
46+
{
47+
// Allocate memory for creating V subsets
48+
int parent[] = new int[graph.V];
49+
50+
// Initialize all subsets as single element sets
51+
for (int i=0; i<graph.V; ++i)
52+
parent[i]=-1;
53+
54+
// Iterate through all edges of graph, find subset of both
55+
// vertices of every edge, if both subsets are same, then
56+
// there is cycle in graph.
57+
for (int i = 0; i < graph.E; ++i)
58+
{
59+
int x = graph.find(parent, graph.edge[i].src);
60+
int y = graph.find(parent, graph.edge[i].dest);
61+
62+
if (x == y)
63+
return 1;
64+
65+
graph.Union(parent, x, y);
66+
}
67+
return 0;
68+
}
69+
70+
// Driver Method
71+
public static void main (String[] args)
72+
{
73+
/* Let us create following graph
74+
0
75+
| \
76+
| \
77+
1-----2 */
78+
int V = 3, E = 3;
79+
Graph graph = new Graph(V, E);
80+
81+
// add edge 0-1
82+
graph.edge[0].src = 0;
83+
graph.edge[0].dest = 1;
84+
85+
// add edge 1-2
86+
graph.edge[1].src = 1;
87+
graph.edge[1].dest = 2;
88+
89+
// add edge 0-2
90+
graph.edge[2].src = 0;
91+
graph.edge[2].dest = 2;
92+
93+
if (graph.isCycle(graph)==1)
94+
System.out.println( "graph contains cycle" );
95+
else
96+
System.out.println( "graph doesn't contain cycle" );
97+
}
98+
}

0 commit comments

Comments
 (0)