Redundant Connection

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

Example 2:

Input: [[1,2], [2,3], [3,4], [1,4], [1,5]]
Output: [1,4]
Explanation: The given undirected graph will be like this:
5 - 1 - 2
    |   |
    4 - 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.

FROM:
LeetCode-Algorithms-graph

Hint:
这道题说是要把图上的一条边删去,把无向图变成一颗树。但事实上,从题目最后说“如果有多种选择选择后出现的一种”可以知道,其实是要一条条边加进去,去画一棵树。那这样我们每次新加一条边,就要判断一下,会不会构成环路。如果构成回路,就说明这条新边就是我们要删除的边。
那么,怎么判断是否构成回路呢?构成回路的条件是很显然的,新加入的边所对应的两个节点中间有通路。当然如果要去遍历树看看是否有通路,这样的开销太大了。我们试着想一下,在加入这条边之前,这个无向图是一个森林或者一棵树,如果两个节点之间有通路,那么它们必然在一棵树上,那么它们必然有一个共同的祖先,即树根。
这样我们只要维护一个数组,记录节点的祖先节点,每次加入新边时,判断两个节点的祖先节点是否相同即可。当然我们判断祖先是否相同时,一定要判断节点辈分最高的祖先。

class Solution {
public:
    vector<int> findRedundantConnection(vector<vector<int>>& edges) {
        int *parent = new int[edges.size()+1];
        for (int i = 0; i < edges.size()+1; i++) {
            parent[i] = i;
        }
        int p1, p2;
        for (auto e : edges) {
            p1 = getParent(e[0], parent);
            p2 = getParent(e[1], parent);
            if (p1 == p2) {
                return e;
            } else {
                parent[p2] = p1;
            }
        }
        vector<int> no;
        return no;
    }

    int getParent(int a, int *parent) {
        if (a != parent[a]) {
            parent[a] = getParent(parent[a], parent);
        }
        return parent[a];
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值