Union find problem:
Problem Statement: Suppose we have set of "n" nodes, if we want to connect them or if we want to check whether we have connection between these two nodes, then code below helps to find in the simplest way.
E.g.
/**
* @author akash mahakode
* @email akash.mahakode@gmail.com
* http://issuesifaced.blogspot.in/
*
*/
public class UnionFind {
int [] inputArr;
public static void main(String args[]){
UnionFind uf = new UnionFind(10);
boolean result = uf.isConnected(1, 9);
System.out.println("Are 1 and 9 connected? \nAns: "+ result);
uf.union(1, 9);
result = uf.isConnected(1, 9);
System.out.println("Are 1 and 9 connected? \nAns: "+ result);
result = uf.isConnected(1, 6);
System.out.println("Are 1 and 6 connected? \nAns: "+ result);
uf.union(1, 6);
result = uf.isConnected(1, 6);
System.out.println("Are 1 and 6 connected? \nAns: "+ result);
result = uf.isConnected(2, 6);
System.out.println("Are 2 and 6 connected? \nAns: "+ result);
uf.union(2, 6);
result = uf.isConnected(2, 6);
System.out.println("Are 1 and 6 connected? \nAns: "+ result);
result = uf.isConnected(2, 9);
System.out.println("Are 2 and 9 connected? \nAns: "+ result);
uf.print();
}
private void print() {
for (int i = 0; i < inputArr.length; i++) {
System.out.print(i+" ");
}
System.out.println();
for (int i = 0; i < inputArr.length; i++) {
System.out.print(inputArr[i]+" ");
}
}
/**
* Constructor which will initialize the input array to 0 to (size -1)
* e.g
* 0 1 2 3 4 5 6 7 8 9
* ---------------------
* |0|1|2|3|4|5|6|7|8|9|
* ---------------------
*
* @param size
*/
public UnionFind(int size){
inputArr = new int[size];
//initialize inputArr
System.out.println("Initial array:");
for (int i = 0; i < inputArr.length; i++) {
inputArr[i] = i;
System.out.print(inputArr[i]+" ");
}
System.out.println();
}
/**
* @param a
* @param b
* @return true when a and b are connected directly or indirectly
*/
public boolean isConnected(int a, int b){
return (inputArr[a] == inputArr[b]);
}
/** connects a and b, that is it changes a to b in the array
* @param a
* @param b
*/
public void union(int a, int b){
int p = inputArr[a];
int q = inputArr[b];
for (int i = 0; i < inputArr.length; i++) {
if(inputArr[i] == p){
inputArr[i] = q;
}
}
}
}