Redundant connection java (and check set)

In this problem, the tree refers to a connected and acyclic undirected graph.

Enter a graph, which consists of a tree with N nodes (the node value does not repeat 1, 2, …, N) and an additional edge. The two vertices of the additional edge are contained between 1 and N, and this additional edge does not belong to an existing edge in the tree.

The resulting graph is a two-dimensional array of edges. The elements of each edge are a pair of [u, v], satisfying u <v, representing the edges of the undirected graph connecting vertices u and v.

Return an edge that can be deleted so that the resulting graph is a tree with N nodes. If there are multiple answers, the last edge in the two-dimensional array is returned. The answer side [u, v] should satisfy the same format u <v.

Example 1:

Input: [[1,2], [1,3], [2,3]]
Output: [2,3]
Explanation: The given undirected graph is:
1
/
2-3
Example 2:

Input: [[1,2], [2,3], [3,4], [1,4], [1,5]]
Output: [1,4]
Explanation: The given undirected graph is:
5-1-2
| |
4-3
Note:

The size of the input two-dimensional array is 3 to 1000.
The integers in the two-dimensional array are between 1 and N, where N is the size of the input array.
Update (2017-09-26):
We have re-checked the problem description and test cases, and it is clear that the graph is an undirected graph. For directed graphs, see Redundant Connection II for details. We apologize for any inconvenience caused.

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/redundant-connection
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Idea: Hahahahahaha, today this set of previous templates has been made. Set of templates for the number of provinces (in fact, two methods)

class Solution {
    
    
    public int[] findRedundantConnection(int[][] edges) {
    
    
        int len = edges.length;
        int[] parent = new int[len+1];
        for(int i=0;i<=len;i++)
        {
    
    
            parent[i] = i;
        }
        for(int i=0;i<len;i++)
        {
    
    
            int[] edge = edges[i];
            int node1 = edge[0];
            int node2 = edge[1];
            //如果没有共同的祖先,那就更新一下
            if(find(parent,node1)!=find(parent,node2)){
    
    
                union(parent,node1,node2);
            }else{
    
    //有共同的祖先,那就say goodbye
                return edge;
            }
        }
        return new int[0];
    }
    //这下面的是模板
    public void union(int[] parent,int index1,int index2){
    
    
        parent[find(parent,index1)] = find(parent,index2);
    }
    
    public int find(int[] parent,int index)
    {
    
    
        if(parent[index]!=index)
        {
    
    
            parent[index] = find(parent,parent[index]);
        }
        return parent[index];
    }
}

Guess you like

Origin blog.csdn.net/weixin_43824233/article/details/112556293