Given n
nodes in a graph labeled from 1
to n
. There is no edges in the graph at beginning.
You need to support the following method:
1. connect(a, b)
, an edge to connect node a and node b
2. query()
, Returns the number of connected component in the graph
Example
5 // n = 5
query() return 5
connect(1, 2)
query() return 4
connect(2, 4)
query() return 3
connect(1, 4)
query() return 3
1 class UnionFind { 2 private int[] father = null; 3 private int count = 0; 4 public UnionFind(int n){ 5 father = new int[n]; 6 count = n; 7 for(int i = 0; i < n; i++){ 8 father[i] = i; 9 } 10 } 11 public int find(int x){ 12 if(father[x] == x){ 13 return x; 14 } 15 return father[x] = find(father[x]); 16 } 17 public void connect(int a, int b){ 18 int root_a = find(a); 19 int root_b = find(b); 20 if(root_a != root_b){ 21 father[root_a] = root_b; 22 count--; 23 } 24 } 25 public int queryUnionCount(){ 26 return count; 27 } 28 } 29 public class ConnectingGraph3 { 30 private UnionFind uf = null; 31 public ConnectingGraph3(int n) { 32 uf = new UnionFind(n); 33 } 34 35 public void connect(int a, int b) { 36 uf.connect(a - 1, b - 1); 37 } 38 39 public int query() { 40 return uf.queryUnionCount(); 41 } 42 }