• [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
    

    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.

    Update (2017-09-26):
    We have overhauled the problem description + test cases and specified clearly the graph is an undirected graph. For the directedgraph follow up please see Redundant Connection II). We apologize for any inconvenience caused.

    给一个无向图,删掉组成环的最后一条边。跟之前的261. Graph Valid Tree 类似,三种解法都基本相同。

    解法:Union Find

    Java:

    class Solution {
        public int[] findRedundantConnection(int[][] edges) {
            int[] parent = new int[2001];
            for (int i = 0; i < parent.length; i++) parent[i] = i;
            
            for (int[] edge: edges){
                int f = edge[0], 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];
        }
    } 

    Python:

    class UnionFind(object):
        def __init__(self, n):
            self.set = range(n)
            self.count = n
    
        def find_set(self, x):
            if self.set[x] != x:
                self.set[x] = self.find_set(self.set[x])  # path compression.
            return self.set[x]
    
        def union_set(self, x, y):
            x_root, y_root = map(self.find_set, (x, y))
            if x_root == y_root:
                return False
            self.set[min(x_root, y_root)] = max(x_root, y_root)
            self.count -= 1
            return True
    
    
    class Solution(object):
        def findRedundantConnection(self, edges):
            """
            :type edges: List[List[int]]
            :rtype: List[int]
            """
            union_find = UnionFind(len(edges)+1)
            for edge in edges:
                if not union_find.union_set(*edge):
                    return edge
            return []  

    C++:

    class Solution {
    public:
        vector<int> findRedundantConnection(vector<vector<int>>& edges) {
            unordered_map<int, unordered_set<int>> m;
            for (auto edge : edges) {
                if (hasCycle(edge[0], edge[1], m, -1)) return edge;
                m[edge[0]].insert(edge[1]);
                m[edge[1]].insert(edge[0]);
            }
            return {};
        }
        bool hasCycle(int cur, int target, unordered_map<int, unordered_set<int>>& m, int pre) {
            if (m[cur].count(target)) return true;
            for (int num : m[cur]) {
                if (num == pre) continue;
                if (hasCycle(num, target, m, cur)) return true;
            }
            return false;
        }
    };
    

    C++:

    class Solution {
    public:
        vector<int> findRedundantConnection(vector<vector<int>>& edges) {
            unordered_map<int, unordered_set<int>> m;
            for (auto edge : edges) {
                queue<int> q{{edge[0]}};
                unordered_set<int> s{{edge[0]}};
                while (!q.empty()) {
                    auto t = q.front(); q.pop();
                    if (m[t].count(edge[1])) return edge;
                    for (int num : m[t]) {
                        if (s.count(num)) continue;
                        q.push(num);
                        s.insert(num);
                    }
                }
                m[edge[0]].insert(edge[1]);
                m[edge[1]].insert(edge[0]);
            }
            return {};
        }
    };
    

    C++:  

    class Solution {
    public:
        vector<int> findRedundantConnection(vector<vector<int>>& edges) {
            unordered_map<int, unordered_set<int>> m;
            for (auto edge : edges) {
                queue<int> q{{edge[0]}};
                unordered_set<int> s{{edge[0]}};
                while (!q.empty()) {
                    auto t = q.front(); q.pop();
                    if (m[t].count(edge[1])) return edge;
                    for (int num : m[t]) {
                        if (s.count(num)) continue;
                        q.push(num);
                        s.insert(num);
                    }
                }
                m[edge[0]].insert(edge[1]);
                m[edge[1]].insert(edge[0]);
            }
            return {};
        }
    };
    

      

      

    类似题目:

    [LeetCode] 261. Graph Valid Tree 图是否是树

    [LeetCode] 685. Redundant Connection II 冗余的连接 II

    All LeetCode Questions List 题目汇总

  • 相关阅读:
    JS-记住用户名【cookie封装引申】
    JS-cookie封装
    JS-比较函数中嵌套函数,可以排序【对象数组】
    JS-随机div颜色
    JS-过滤敏感词【RegExp】
    JS-提取字符串—>>普通方法VS正则表达式
    CSS- ie6,ie7,ie8 兼容性写法,CSS hack写法
    JS-【同页面多次调用】轮播特效封装-json传多个参数
    JS-【同页面多次调用】tab选项卡封装
    Redis主从同步
  • 原文地址:https://www.cnblogs.com/lightwindy/p/9750317.html
Copyright © 2020-2023  润新知