leetcode 684. Redundant Connection(多余的连接)

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;
    }

参考资料

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值