MCPcopy Create free account
hub / github.com/Tiwarishashwat/InterviewCodes / DisjointSet

Class DisjointSet

SatisfiabilityOfEqualityEquations.java:28–64  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

26
27
28public class DisjointSet {
29 int parent[];
30 int size[];
31 DisjointSet(int nodes){
32 this.parent = new int[nodes];
33 this.size = new int[nodes];
34 for(int i=0;i<nodes;i++){
35 this.parent[i] = i;
36 this.size[i] = 1;
37 }
38 }
39
40 public int findRootParent(int node){
41 if(node == parent[node]){
42 return node;
43 }
44 parent[node] = findRootParent(parent[node]);
45 return parent[node];
46 }
47 public boolean unionBySize(int node1, int node2){
48 //1. find the root parent
49 int rootParent1 = findRootParent(node1);
50 int rootParent2 = findRootParent(node2);
51 if(rootParent1==rootParent2){
52 return false;
53 }
54 // 2, union of components
55 if(size[rootParent1]<size[rootParent2]){
56 parent[rootParent1] = rootParent2;
57 size[rootParent2] += size[rootParent1];
58 }else {
59 parent[rootParent2] = rootParent1;
60 size[rootParent1] += size[rootParent2];
61 }
62 return true;
63 }
64}
65
66
67

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected