| 15 | } |
| 16 | |
| 17 | public class DisjointSet { |
| 18 | int parent[]; |
| 19 | int size[]; |
| 20 | DisjointSet(int nodes){ |
| 21 | this.parent = new int[nodes]; |
| 22 | this.size = new int[nodes]; |
| 23 | for(int i=0;i<nodes;i++){ |
| 24 | this.parent[i] = i; |
| 25 | this.size[i] = 1; |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | public int findRootParent(int node){ |
| 30 | if(node == parent[node]){ |
| 31 | return node; |
| 32 | } |
| 33 | parent[node] = findRootParent(parent[node]); |
| 34 | return parent[node]; |
| 35 | } |
| 36 | public boolean unionBySize(int node1, int node2){ |
| 37 | //1. find the root parent |
| 38 | int rootParent1 = findRootParent(node1); |
| 39 | int rootParent2 = findRootParent(node2); |
| 40 | if(rootParent1==rootParent2){ |
| 41 | return false; |
| 42 | } |
| 43 | // 2, union of components |
| 44 | if(size[rootParent1]<size[rootParent2]){ |
| 45 | parent[rootParent1] = rootParent2; |
| 46 | size[rootParent2] += size[rootParent1]; |
| 47 | }else { |
| 48 | parent[rootParent2] = rootParent1; |
| 49 | size[rootParent1] += size[rootParent2]; |
| 50 | } |
| 51 | return true; |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | |
| 56 |
nothing calls this directly
no outgoing calls
no test coverage detected