[Leetcode] 684. Redundant Connection redundant connections

Source: Internet
Author: User

In this problem, a tree was an undirected graph, which is connected and have no cycles.

The given input is a graph this started as a tree with N nodes (with distinct values 1, 2, ..., n), with one additional Ed GE added. The added edge has a different vertices chosen from 1 to N, and is not a edge that already existed.

The resulting graph is given as a 2d-array of edges . Each element edges of was a pair [u, v] u < v with, which represents an undirected edge connecting nodes and u v .

Return an edge, can be removed so, the resulting graph is a tree of N nodes. If There is multiple answers, return the answer that occurs last in the given 2d-array. The answer Edge [u, v] should is in the same format, with u < v .

Example 1:

Input: [[up], [1,3], [2,3]]output: [2,3]explanation:the given undirected graph would be ' like this:  1/2-3

Example 2:

Input: [[up], [2,3], [3,4], [1,4], [1,5]]output: [1,4]explanation:the given undirected graph would be is like This:5-1-2    |   |    4-3

Note:

    • The size of the input 2d-array would be between 3 and 1000.
    • Every integer represented in the 2d-array would be a 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 was an undirected graph. For the directedgraph follow up, see redundant Connection II). We apologize for any inconvenience caused.

Give an image without a direction, and delete the last edge of the constituent ring. With the previous 261. Graph Valid Tree is similar, three kinds of solutions are basically the same.

Solution: 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 Trueclass 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 {};    }};

  

  

Similar topics:

[Leetcode] 261. Whether the graph Valid tree

[Leetcode] 685. Redundant Connection II Redundant Connection II

[Leetcode] 684. Redundant Connection redundant connections

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.