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