{"id":449,"date":"2017-09-28T20:54:42","date_gmt":"2017-09-29T03:54:42","guid":{"rendered":"http:\/\/zxi.mytechroad.com\/blog\/?p=449"},"modified":"2018-04-19T08:29:05","modified_gmt":"2018-04-19T15:29:05","slug":"leetcode-684-redundant-connection","status":"publish","type":"post","link":"https:\/\/zxi.mytechroad.com\/blog\/tree\/leetcode-684-redundant-connection\/","title":{"rendered":"\u82b1\u82b1\u9171 LeetCode 684. Redundant Connection"},"content":{"rendered":"<p><iframe loading=\"lazy\" title=\"\u82b1\u82b1\u9171 LeetCode 684. Redundant Connection - \u5237\u9898\u627e\u5de5\u4f5c EP74\" width=\"500\" height=\"375\" src=\"https:\/\/www.youtube.com\/embed\/4hJ721ce010?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe><\/p>\n<p><a href=\"https:\/\/leetcode.com\/problems\/redundant-connection\/description\/\">https:\/\/leetcode.com\/problems\/redundant-connection\/description\/<\/a><\/p>\n<p><strong>Problem:<\/strong><\/p>\n<p>In this problem, a tree is an\u00a0<b>undirected<\/b>\u00a0graph that is connected and has no cycles.<\/p>\n<p>The given input is a graph that started as a tree with N nodes (with distinct values 1, 2, &#8230;, 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.<\/p>\n<p>The resulting graph is given as a 2D-array of\u00a0<code>edges<\/code>. Each element of\u00a0<code>edges<\/code>\u00a0is a pair\u00a0<code>[u, v]<\/code>\u00a0with\u00a0<code>u &lt; v<\/code>, that represents an\u00a0<b>undirected<\/b>\u00a0edge connecting nodes\u00a0<code>u<\/code>\u00a0and\u00a0<code>v<\/code>.<\/p>\n<p>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\u00a0<code>[u, v]<\/code>\u00a0should be in the same format, with\u00a0<code>u &lt; v<\/code>.<\/p>\n<p><b>Example 1:<\/b><\/p>\n<pre class=\"\">Input: [[1,2], [1,3], [2,3]]\r\nOutput: [2,3]\r\nExplanation: The given undirected graph will be like this:\r\n  1\r\n \/ \\\r\n2 - 3\r\n<\/pre>\n<p><b>Example 2:<\/b><\/p>\n<pre class=\"\">Input: [[1,2], [2,3], [3,4], [1,4], [1,5]]\r\nOutput: [1,4]\r\nExplanation: The given undirected graph will be like this:\r\n5 - 1 - 2\r\n    |   |\r\n    4 - 3\r\n<\/pre>\n<p><b>Note:<\/b><\/p>\n<p>&nbsp;<\/p>\n<ul>\n<li>The size of the input 2D-array will be between 3 and 1000.<\/li>\n<li>Every integer represented in the 2D-array will be between 1 and N, where N is the size of the input array.<\/li>\n<\/ul>\n<p><script async src=\"\/\/pagead2.googlesyndication.com\/pagead\/js\/adsbygoogle.js\"><\/script><br \/>\n<ins class=\"adsbygoogle\" style=\"display: block; text-align: center;\" data-ad-layout=\"in-article\" data-ad-format=\"fluid\" data-ad-client=\"ca-pub-2404451723245401\" data-ad-slot=\"7983117522\"><\/ins><br \/>\n<script>\n     (adsbygoogle = window.adsbygoogle || []).push({});\n<\/script><\/p>\n<p><strong>Idea:<\/strong><br \/>\nDFS \/ Union-Find<\/p>\n<p><a href=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/684-ep74-1.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-454\" src=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/684-ep74-1.png\" alt=\"\" width=\"960\" height=\"540\" srcset=\"https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/684-ep74-1.png 960w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/684-ep74-1-300x169.png 300w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/684-ep74-1-768x432.png 768w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/684-ep74-1-624x351.png 624w\" sizes=\"auto, (max-width: 960px) 100vw, 960px\" \/><\/a><\/p>\n<p><a href=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/684-ep74-2.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-453\" src=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/684-ep74-2.png\" alt=\"\" width=\"960\" height=\"540\" srcset=\"https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/684-ep74-2.png 960w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/684-ep74-2-300x169.png 300w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/684-ep74-2-768x432.png 768w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/684-ep74-2-624x351.png 624w\" sizes=\"auto, (max-width: 960px) 100vw, 960px\" \/><\/a><\/p>\n<p>&nbsp;<\/p>\n<p><strong>Solutions:<\/strong><\/p>\n<p>C++ \/ DFS<\/p>\n<pre class=\"lang:c++ decode:true\">\/\/ Author: Huahua\r\n\/\/ Time Complexity: O(n^2)\r\n\/\/ Running Time: 22 ms\r\nclass Solution {\r\npublic:\r\n    vector&lt;int&gt; findRedundantConnection(vector&lt;vector&lt;int&gt;&gt;&amp; edges) {\r\n        unordered_map&lt;int, vector&lt;int&gt;&gt; graph;\r\n        for (const auto&amp; edge : edges) {\r\n            int u = edge[0];\r\n            int v = edge[1];\r\n            \r\n            unordered_set&lt;int&gt; visited;\r\n            if (hasPath(u, v, graph, visited))\r\n                return edge;\r\n            \r\n            graph[u].push_back(v);\r\n            graph[v].push_back(u);\r\n        }\r\n        return {};\r\n    }\r\nprivate:\r\n    bool hasPath(int curr, \r\n                 int goal, \r\n                 const unordered_map&lt;int, vector&lt;int&gt;&gt;&amp; graph, \r\n                 unordered_set&lt;int&gt;&amp; visited) {\r\n        if (curr == goal) return true;\r\n        visited.insert(curr);\r\n        if (!graph.count(curr) || !graph.count(goal)) return false;\r\n        for (int next : graph.at(curr)) {\r\n            if (visited.count(next)) continue;\r\n            if (hasPath(next, goal, graph, visited)) return true;\r\n        }\r\n        return false;\r\n    }\r\n};<\/pre>\n<p>&nbsp;<\/p>\n<p>C++ \/ Union Find<\/p>\n<pre class=\"lang:c++ decode:true\">\/\/ Author: Huahua\r\n\/\/ Running time: 6 ms\r\nclass UnionFindSet {\r\npublic:\r\n    UnionFindSet(int n) {\r\n        ranks_ = vector&lt;int&gt;(n + 1, 0);        \r\n        parents_ = vector&lt;int&gt;(n + 1, 0);                \r\n        \r\n        for (int i = 0; i &lt; parents_.size(); ++i)\r\n            parents_[i] = i;\r\n    }\r\n    \r\n    \/\/ Merge sets that contains u and v.\r\n    \/\/ Return true if merged, false if u and v are already in one set.\r\n    bool Union(int u, int v) {\r\n        int pu = Find(u);\r\n        int pv = Find(v);\r\n        if (pu == pv) return false;\r\n        \r\n        \/\/ Meger low rank tree into high rank tree\r\n        if (ranks_[pv] &gt; ranks_[pu])\r\n            parents_[pu] = pv;           \r\n        else if (ranks_[pu] &gt; ranks_[pv])\r\n            parents_[pv] = pu;\r\n        else {\r\n            parents_[pv] = pu;\r\n            ranks_[pv] += 1;\r\n        }\r\n        \r\n        return true;\r\n    }\r\n    \r\n    \/\/ Get the root of u.\r\n    int Find(int u) {        \r\n        \/\/ Compress the path during traversal\r\n        if (u != parents_[u])\r\n            parents_[u] = Find(parents_[u]);        \r\n        return parents_[u];\r\n    }\r\nprivate:\r\n    vector&lt;int&gt; parents_;\r\n    vector&lt;int&gt; ranks_;\r\n};\r\n\r\nclass Solution {\r\npublic:\r\n    vector&lt;int&gt; findRedundantConnection(vector&lt;vector&lt;int&gt;&gt;&amp; edges) {    \r\n        UnionFindSet s(edges.size());\r\n        \r\n        for(const auto&amp; edge: edges)\r\n            if (!s.Union(edge[0], edge[1]))\r\n                return edge;\r\n        \r\n        return {};\r\n    }\r\n};<\/pre>\n<p>Java \/ Union Find<\/p>\n<pre class=\"lang:java decode:true\">\/\/ Author: Huahua\r\n\/\/ Runtime: 6 ms\r\nclass Solution {\r\n    class UnionFindSet {\r\n        private int[] parents_;\r\n        private int[] ranks_;\r\n\r\n        public UnionFindSet(int n) {\r\n            parents_ = new int[n + 1];\r\n            ranks_ = new int[n + 1];\r\n            for (int i = 0; i &lt; parents_.length; ++i) {\r\n                parents_[i] = i;\r\n                ranks_[i] = 1;\r\n            }\r\n        }\r\n\r\n        public boolean Union(int u, int v) {\r\n            int pu = Find(u);\r\n            int pv = Find(v);\r\n            if (pu == pv) return false;\r\n\r\n            if (ranks_[pv] &gt; ranks_[pu])\r\n                parents_[pu] = pv;           \r\n            else if (ranks_[pu] &gt; ranks_[pv])\r\n                parents_[pv] = pu;\r\n            else {\r\n                parents_[pv] = pu;\r\n                ranks_[pu] += 1;\r\n            }\r\n\r\n            return true;\r\n        }\r\n\r\n        public int Find(int u) {\r\n            while (parents_[u] != u) {\r\n                parents_[u] = parents_[parents_[u]];\r\n                u = parents_[u];\r\n            }\r\n            return u;\r\n        }\r\n    }\r\n    \r\n    public int[] findRedundantConnection(int[][] edges) {\r\n        UnionFindSet s = new UnionFindSet(edges.length);\r\n        for (int[] edge : edges)\r\n            if (!s.Union(edge[0], edge[1]))\r\n                return edge;\r\n        return null;\r\n    }\r\n    \r\n    \r\n}<\/pre>\n<p>&nbsp;<\/p>\n<p>Python: Union Find<\/p>\n<pre class=\"lang:python decode:true \">\"\"\"\r\nAuthor: Huahua\r\nRunning Time: 66 ms\r\n\"\"\"\r\nclass Solution:\r\n    def findRedundantConnection(self, edges):\r\n        \r\n        p = [0]*(len(edges) + 1)\r\n        s = [1]*(len(edges) + 1)\r\n        \r\n        def find(u):\r\n            while p[u] != u:\r\n                p[u] = p[p[u]]\r\n                u = p[u]\r\n            return u\r\n        \r\n        for u, v in edges:\r\n            if p[u] == 0: p[u] = u\r\n            if p[v] == 0: p[v] = v\r\n            pu, pv = find(u), find(v)\r\n            if pu == pv: return [u, v]\r\n            \r\n            if s[pv] &gt; s[pu]: u, v = v, u\r\n            p[pv] = pu\r\n            s[pu] += s[pv]\r\n\r\n        return []<\/pre>\n<p>Python \/ Union Find V2<\/p>\n<pre class=\"lang:python decode:true\">\"\"\"\r\nAuthor: Huahua\r\nRuntime: 59 ms (&lt;92.42%)\r\n\"\"\"\r\nclass UnionFindSet:\r\n    def __init__(self, n):\r\n        self._parents = [i for i in range(n + 1)]\r\n        self._ranks = [1 for i in range(n + 1)]\r\n    \r\n    def find(self, u):\r\n        while u != self._parents[u]:\r\n            self._parents[u] = self._parents[self._parents[u]]\r\n            u = self._parents[u]\r\n        return u\r\n    \r\n    def union(self, u, v):\r\n        pu, pv = self.find(u), self.find(v)\r\n        if pu == pv: return False\r\n        \r\n        if self._ranks[pu] &lt; self._ranks[pv]:\r\n            self._parents[pu] = pv\r\n        elif self._ranks[pu] &gt; self._ranks[pv]:\r\n            self._parents[pv] = pu\r\n        else:        \r\n            self._parents[pv] = pu\r\n            self._ranks[pu] += 1\r\n        \r\n        return True\r\n        \r\nclass Solution:\r\n    def findRedundantConnection(self, edges):\r\n        s = UnionFindSet(len(edges))\r\n        for edge in edges:\r\n            if not s.union(edge[0], edge[1]): return edge\r\n        return None\r\n        ndSet(len(edges))\r\n        for edge in edges:\r\n            if not s.union(edge[0], edge[1]): return edge\r\n        return None\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>https:\/\/leetcode.com\/problems\/redundant-connection\/description\/ Problem: In this problem, a tree is an\u00a0undirected\u00a0graph that is connected and has no cycles. The given input is a graph that started as&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[76,45],"tags":[102,33,113],"class_list":["post-449","post","type-post","status-publish","format-standard","hentry","category-graph","category-tree","tag-connected-components","tag-dfs","tag-union-find","entry","simple"],"_links":{"self":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/449","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/comments?post=449"}],"version-history":[{"count":14,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/449\/revisions"}],"predecessor-version":[{"id":2561,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/449\/revisions\/2561"}],"wp:attachment":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/media?parent=449"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/categories?post=449"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/tags?post=449"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}