1. Topic
https://leetcode-cn.com/problems/redundant-connection/
2. problem solution
This question is the essence Let N nodes with the ring removed undirected graph into a tree method edge nodes N (that is to remove the ring) by. So get rid of this feature side is that he is one of the two points are attached to the other side of the point. If there is only three points, then the vertex points of the two sides of the same shall be a point; if it is more points, then you can use that smaller nodes to the larger of the node. Until the case of conditions are met. It can be the result.
3. Code
class Solution {
public int[] findRedundantConnection(int[][] edges) {
int[] parent = new int[1001];
//父节点
for (int i = 0; i < parent.length; i++){
parent[i] = i;
}
//遍历
for (int[] edge: edges){
int f = edge[0];
int t = edge[1];
if (find(parent, f) == find(parent, t)) return edge;
else parent[find(parent, f)] = find(parent, t);
}
return new int[2];
}
//查找父节点
private int find(int[] parent, int f) {
if (f != parent[f]) {
parent[f] = find(parent, parent[f]);
}
return parent[f];
}
}
4. Results screenshot
Reproduced in: https: //www.jianshu.com/p/73bb2afd7883