package com.heu.wsq.leetcode.graph;
public class FindRedundantConnection {
public int[] findRedundantConnection(int[][] edges){
int n = edges.length;
UnionFind unionFind = new UnionFind(n);
for (int i = 0; i < n; i++){
int[] edge = edges[i];
if (unionFind.isConnected(edge[0], edge[1])){
return edge;
}
unionFind.union(edge[0], edge[1]);
}
return new int[0];
}
private class UnionFind{
private int[] parent;
private int[] rank;
public UnionFind(int n){
this.parent = new int[n];
this.rank = new int[n];
for(int i = 0; i < n; i++){
this.parent[i] = i;
this.rank[i] = 1;
}
}
public void union(int x, int y){
x = x - 1;
y = y - 1;
int rootX = find(x);
int rootY = find(y);
if (rootX == rootY){
return;
}
if (this.rank[rootX] == this.rank[rootY]){
this.parent[rootX] = rootY;
this.rank[rootY] += 1;
}else if (this.rank[rootX] > this.rank[rootY]){
this.parent[rootY] = rootX;
}else{
this.parent[rootX] = rootY;
}
}
public int find(int x){
x -= 1;
int r = x;
while (r != this.parent[r]){
r = this.parent[r];
}
int k = x;
while (k != r){
int tmp = this.parent[k];
this.parent[k] = r;
k = tmp;
}
return r;
}
public boolean isConnected(int x, int y){
x -= 1;
y -= 1;
int rootX = find(x);
int rootY = find(y);
return rootX == rootY;
}
}
}