{"id":25960,"date":"2017-10-25T22:03:23","date_gmt":"2017-10-25T16:33:23","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=25960"},"modified":"2017-10-25T22:03:23","modified_gmt":"2017-10-25T16:33:23","slug":"java-programming-union-find-algorithm-set-1-detect-cycle-undirected-graph","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/java-programming-union-find-algorithm-set-1-detect-cycle-undirected-graph\/","title":{"rendered":"Java Programming &#8211; Union-Find Algorithm | Set 1 (Detect Cycle in an Undirected Graph)"},"content":{"rendered":"<p>A <em>disjoint-set data structure<\/em> is a data structure that keeps track of a set of elements partitioned into a number of disjoint (non-overlapping) subsets.<span id=\"more-26350\"><\/span> A <a href=\"http:\/\/en.wikipedia.org\/wiki\/Disjoint-set_data_structure\" target=\"_blank\" rel=\"noopener\"><em>union-find algorithm<\/em><\/a> is an algorithm that performs two useful operations on such a data structure:<\/p>\n<p><em><strong>Find:<\/strong><\/em> Determine which subset a particular element is in. This can be used for determining if two elements are in the same subset.<\/p>\n<p><em><strong>Union:<\/strong><\/em> Join two subsets into a single subset.<\/p>\n<p>In this post, we will discuss an application of Disjoint Set Data Structure. The application is to check whether a given graph contains a cycle or not.<\/p>\n<p><em>Union-Find Algorithm<\/em> can be used to check whether an undirected graph contains cycle or not. Note that we have discussed an <a href=\"http:\/\/www.geeksforgeeks.org\/archives\/18516\" target=\"_blank\" rel=\"noopener\">algorithm to detect cycle<\/a>. This is another method based on <em>Union-Find<\/em>. This method assumes that graph doesn\u2019t contain any self-loops.<br \/>\nWe can keeps track of the subsets in a 1D array, lets call it parent[].<\/p>\n[ad type=&#8221;banner&#8221;]\n<p>Let us consider the following graph:<\/p>\n<p>For each edge, make subsets using both the vertices of the edge. If both the vertices are in the same subset, a cycle is found.<\/p>\n<p>Initially, all slots of parent array are initialized to -1 (means there is only one item in every subset).<\/p>\n<pre>0   1   2\r\n-1 -1  -1<\/pre>\n<p>Now process all edges one by one.<\/p>\n<p><em>Edge 0-1:<\/em> Find the subsets in which vertices 0 and 1 are. Since they are in different subsets, we take the union of them. For taking the union, either make node 0 as parent of node 1 or vice-versa.<\/p>\n<pre>0   1   2    &lt;----- 1 is made parent of 0 (1 is now representative of subset {0, 1})\r\n1  -1  -1<\/pre>\n<p><em>Edge 1-2:<\/em> 1 is in subset 1 and 2 is in subset 2. So, take union.<\/p>\n<pre>0   1   2    &lt;----- 2 is made parent of 1 (2 is now representative of subset {0, 1, 2})\r\n1   2  -1<\/pre>\n<p><em>Edge 0-2:<\/em> 0 is in subset 2 and 2 is also in subset 2. Hence, including this edge forms a cycle.<\/p>\n<p>How subset of 0 is same as 2?<br \/>\n0-&gt;1-&gt;2 \/\/ 1 is parent of 0 and 2 is parent of 1<\/p>\n<p>Based on the above explanation, below are implementations:<\/p>\n<p><strong>Java Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">\/\/ Java Program for union-find algorithm to detect cycle in a graph<br\/>import java.util.*;<br\/>import java.lang.*;<br\/>import java.io.*;<br\/> <br\/>class Graph<br\/>{<br\/>    int V, E;    \/\/ V-&gt; no. of vertices &amp; E-&gt;no.of edges<br\/>    Edge edge[]; \/\/ \/collection of all edges<br\/> <br\/>    class Edge<br\/>    {<br\/>        int src, dest;<br\/>    };<br\/> <br\/>    \/\/ Creates a graph with V vertices and E edges<br\/>    Graph(int v,int e)<br\/>    {<br\/>        V = v;<br\/>        E = e;<br\/>        edge = new Edge[E];<br\/>        for (int i=0; i&lt;e; ++i)<br\/>            edge[i] = new Edge();<br\/>    }<br\/> <br\/>    \/\/ A utility function to find the subset of an element i<br\/>    int find(int parent[], int i)<br\/>    {<br\/>        if (parent[i] == -1)<br\/>            return i;<br\/>        return find(parent, parent[i]);<br\/>    }<br\/> <br\/>    \/\/ A utility function to do union of two subsets<br\/>    void Union(int parent[], int x, int y)<br\/>    {<br\/>        int xset = find(parent, x);<br\/>        int yset = find(parent, y);<br\/>        parent[xset] = yset;<br\/>    }<br\/> <br\/> <br\/>    \/\/ The main function to check whether a given graph<br\/>    \/\/ contains cycle or not<br\/>    int isCycle( Graph graph)<br\/>    {<br\/>        \/\/ Allocate memory for creating V subsets<br\/>        int parent[] = new int[graph.V];<br\/> <br\/>        \/\/ Initialize all subsets as single element sets<br\/>        for (int i=0; i&lt;graph.V; ++i)<br\/>            parent[i]=-1;<br\/> <br\/>        \/\/ Iterate through all edges of graph, find subset of both<br\/>        \/\/ vertices of every edge, if both subsets are same, then<br\/>        \/\/ there is cycle in graph.<br\/>        for (int i = 0; i &lt; graph.E; ++i)<br\/>        {<br\/>            int x = graph.find(parent, graph.edge[i].src);<br\/>            int y = graph.find(parent, graph.edge[i].dest);<br\/> <br\/>            if (x == y)<br\/>                return 1;<br\/> <br\/>            graph.Union(parent, x, y);<br\/>        }<br\/>        return 0;<br\/>    }<br\/> <br\/>    \/\/ Driver Method<br\/>    public static void main (String[] args)<br\/>    {<br\/>        \/* Let us create following graph<br\/>         0<br\/>        |  \\<br\/>        |    \\<br\/>        1-----2 *\/<br\/>        int V = 3, E = 3;<br\/>        Graph graph = new Graph(V, E);<br\/> <br\/>        \/\/ add edge 0-1<br\/>        graph.edge[0].src = 0;<br\/>        graph.edge[0].dest = 1;<br\/> <br\/>        \/\/ add edge 1-2<br\/>        graph.edge[1].src = 1;<br\/>        graph.edge[1].dest = 2;<br\/> <br\/>        \/\/ add edge 0-2<br\/>        graph.edge[2].src = 0;<br\/>        graph.edge[2].dest = 2;<br\/> <br\/>        if (graph.isCycle(graph)==1)<br\/>            System.out.println( &quot;graph contains cycle&quot; );<br\/>        else<br\/>            System.out.println( &quot;graph doesn&#039;t contain cycle&quot; );<br\/>    }<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>graph contains cycle<\/pre>\n<p>Note that the implementation of <em>union()<\/em> and <em>find()<\/em> is naive and takes O(n) time in worst case. These methods can be improved to O(Logn) using <em>Union by Rank or Height<\/em>. We will soon be discussing <em>Union by Rank<\/em> in a separate post.<\/p>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Java Programming &#8211; Union-Find Algorithm | Set 1 (Detect Cycle in an Undirected Graph) &#8211; Graph Algorithms &#8211; A disjoint-set data structure is a data.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1,74168,73906,2139],"tags":[76366,76375,76365,76374,76367,76376,76377,76364],"class_list":["post-25960","post","type-post","status-publish","format-standard","hentry","category-coding","category-dfs-and-bfs","category-graph-algorithms","category-java","tag-union-find-algorithm-c","tag-union-find-complexity","tag-union-find-geeksforgeeks","tag-union-find-java","tag-union-find-path-compression","tag-union-find-princeton","tag-union-find-python","tag-union-find-wiki"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25960","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=25960"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25960\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=25960"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=25960"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=25960"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}