LeetCode 684. 冗余连接
在本问题中, 树指的是一个连通且无环的无向图。
输入一个图,该图由一个有着N个节点 (节点值不重复1, 2, …, N) 的树及一条附加的边构成。附加的边的两个顶点包含在1到N中间,这条附加的边不属于树中已存在的边。
结果图是一个以边组成的二维数组。每一个边的元素是一对[u, v] ,满足 u < v,表示连接顶点u 和v的无向图的边。
返回一条可以删去的边,使得结果图是一个有着N个节点的树。如果有多个答案,则返回二维数组中最后出现的边。答案边 [u, v] 应满足相同的格式 u < v。
题解:
使用并查集,在合并两个节点之前,判断这两个节点是否是联通的,如果是则返回这两条节点之间的边。
class Solution {
public int[] findRedundantConnection(int[][] edges) {
int[] ans = new int[2];
Union u = new Union(edges.length);
for(int[] a : edges){
int x = a[0], y = a[1];
if(!u.union(x,y))
ans = a;
}
return ans;
}
}
class Union{
private int[] father;
public Union(int n){
father = new int[n + 1];
for(int i = 1; i <= n; i++)
{
father[i] = i;
}
}
public boolean union(int x, int y){
int fax = find(x);
int fay = find(y);
if(fax != fay)
father[fax] = fay;
else
return false;
return true;
}
public int find(int x){
if(x != father[x])
return find(father[x]);
return father[x];
}
}
题目来源:https://leetcode-cn.com/problems/redundant-connection/