In this problem, a tree is an undirected graph that is connected and has no cycles.
The given input is a graph that started as a tree with N nodes (with distinct values 1, 2, …, N), with one additional edge added. The added edge has two different vertices chosen from 1 to N, and was not an edge that already existed.
The resulting graph is given as a 2D-array of edges. Each element of edges is a pair [u, v] with u < v, that represents an undirected edge connecting nodes u and v.
Return an edge that can be removed so that the resulting graph is a tree of N nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array. The answer edge [u, v] should be in the same format, with u < v.
Example 1:
Input: [[1,2], [1,3], [2,3]]
Output: [2,3]
Explanation: The given undirected graph will be like this:
1
/ \
2 - 3
Note:
The size of the input 2D-array will be between 3 and 1000.
Every integer represented in the 2D-array will be between 1 and N, where N is the size of the input array.
给出一个无向图,找出第一个构成闭环的边
思路:
可用一个邻接链表保存每条边,DFS搜索闭环,O(N2)
这里参考Union-Find解法
union指的是相同root的节点聚为一类,这些节点指向同一root。
find是给一个节点,找到它的parent,进而找到它的root。
如果一条边,它的两个节点指向同一root,比如例子中的2,3,都指向1,那么2,3这条边就构成了闭环,需要去掉。
union的时候如果出现一长串,1指向2,2指向3,…,为了在find中效率更高,在union的时候要把这一连串的节点都直接指向root,这样在find的时候可以一步到位找到root。
当有两个集合,我们要修改size较小的集合中的节点的parent,这样可以节省开销。所以还要保存每个root所连接的所有节点的size(节点数量)。
刚开始的时候每个节点都指向它自己,它自己就是自己的parent,也是root。
root,parent,node的关系是,node的parent可以是root,也可以是其他节点,而最上面那层parent就是root。
public int[] findRedundantConnection(int[][] edges) {
int m = edges.length;
int[] parent = new int[m+1];
int[] size = new int[m+1];
for(int[] edge : edges) {
int u = edge[0];
int v = edge[1];
if(parent[u] == 0) parent[u] = u;
if(parent[v] == 0) parent[v] = v;
int pu = findParent(u, parent);
int pv = findParent(v, parent);
if(pu == pv) return edge;
//较小size的接到较大size的root上
if(size[pv] > size[pu]) {
//swap pu and pv
int tmp = pv;
pv = pu;
pu = tmp;
}
//v 并入u
parent[pv] = pu;
size[pu] += size[pv];
}
return new int[]{};
}
int findParent(int node, int[] parent) {
while(parent[node] != node) {
parent[node] = parent[parent[node]];
node = parent[node];
}
return node;
}