{"id":25992,"date":"2017-10-26T09:27:36","date_gmt":"2017-10-26T03:57:36","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=25992"},"modified":"2018-10-27T17:32:59","modified_gmt":"2018-10-27T12:02:59","slug":"java-algorithm-detect-cycle-undirected-graph-2","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/java-algorithm-detect-cycle-undirected-graph-2\/","title":{"rendered":"Detect cycle in an undirected graph"},"content":{"rendered":"<h4 id=\"given-an-undirected-graph-how-to-check-if-there-is-a-cycle-in-the-graph\">Given an undirected graph, how to check if there is a cycle in the graph?<\/h4>\n<h3 id=\"java-algorithm-detect-cycle-in-an-undirected-graph\"><span style=\"color: #003300;\">Java Algorithm &#8211; Detect cycle in an undirected graph<\/span><\/h3>\n<p><strong>For example<\/strong>, the following <a href=\"https:\/\/www.wikitechy.com\/tutorials\/javascript\/graph-visualization-libe-rary-in-javascript\" target=\"_blank\" rel=\"noopener\">graph<\/a> has a cycle 1-0-2-1.<\/p>\n<p>The time complexity of the union-find algorithm is <strong>O(ELogV)<\/strong>. Like <a href=\"https:\/\/www.wikitechy.com\/technology\/detect-cycle-directed-graph-using-colors\/\" target=\"_blank\" rel=\"noopener\">directed graphs<\/a>, we can use <strong>DFS<\/strong> to detect cycle in an undirected graph in <strong>O(V+E)<\/strong> time. We do a DFS traversal of the given graph. For every visited vertex \u2018v\u2019, if there is an adjacent \u2018u\u2019 such that u is already visited and u is not parent of v, then there is a cycle in graph. If we don\u2019t find such an adjacent for any vertex, we say that there is no cycle. The assumption of this approach is that there are no parallel edges between any two vertices.<\/p>\n<p><img decoding=\"async\" class=\"aligncenter wp-image-31591 size-full\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/10\/detect-undirected-graph-cycle.png\" alt=\"detect-undirected-graph-cycle\" width=\"300\" height=\"156\" \/><\/p>\n<p>The program is given in <a href=\"https:\/\/www.wikitechy.com\/tutorials\/java\/java-hello-world-example\" target=\"_blank\" rel=\"noopener\">Java program<\/a>, as follows<\/p>\n<h4 id=\"java-programming\"><span style=\"color: #008080;\"><strong>Java Programming:<\/strong><\/span><\/h4>\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\">\/\/ A Java Program to detect cycle in an undirected graph<br\/>import java.io.*;<br\/>import java.util.*;<br\/> <br\/>\/\/ This class represents a directed graph using adjacency list<br\/>\/\/ representation<br\/>class Graph<br\/>{<br\/>    private int V;   \/\/ No. of vertices<br\/>    private LinkedList&lt;Integer&gt; adj[]; \/\/ Adjacency List Represntation<br\/> <br\/>    \/\/ Constructor<br\/>    Graph(int v) {<br\/>        V = v;<br\/>        adj = new LinkedList[v];<br\/>        for(int i=0; i&lt;v; ++i)<br\/>            adj[i] = new LinkedList();<br\/>    }<br\/> <br\/>    \/\/ Function to add an edge into the graph<br\/>    void addEdge(int v,int w) {<br\/>        adj[v].add(w);<br\/>        adj[w].add(v);<br\/>    }<br\/> <br\/>    \/\/ A recursive function that uses visited[] and parent to detect<br\/>    \/\/ cycle in subgraph reachable from vertex v.<br\/>    Boolean isCyclicUtil(int v, Boolean visited[], int parent)<br\/>    {<br\/>        \/\/ Mark the current node as visited<br\/>        visited[v] = true;<br\/>        Integer i;<br\/> <br\/>        \/\/ Recur for all the vertices adjacent to this vertex<br\/>        Iterator&lt;Integer&gt; it = adj[v].iterator();<br\/>        while (it.hasNext())<br\/>        {<br\/>            i = it.next();<br\/> <br\/>            \/\/ If an adjacent is not visited, then recur for that<br\/>            \/\/ adjacent<br\/>            if (!visited[i])<br\/>            {<br\/>                if (isCyclicUtil(i, visited, v))<br\/>                    return true;<br\/>            }<br\/> <br\/>            \/\/ If an adjacent is visited and not parent of current<br\/>            \/\/ vertex, then there is a cycle.<br\/>            else if (i != parent)<br\/>                return true;<br\/>        }<br\/>        return false;<br\/>    }<br\/> <br\/>    \/\/ Returns true if the graph contains a cycle, else false.<br\/>    Boolean isCyclic()<br\/>    {<br\/>        \/\/ Mark all the vertices as not visited and not part of<br\/>        \/\/ recursion stack<br\/>        Boolean visited[] = new Boolean[V];<br\/>        for (int i = 0; i &lt; V; i++)<br\/>            visited[i] = false;<br\/> <br\/>        \/\/ Call the recursive helper function to detect cycle in<br\/>        \/\/ different DFS trees<br\/>        for (int u = 0; u &lt; V; u++)<br\/>            if (!visited[u]) \/\/ Don&#039;t recur for u if already visited<br\/>                if (isCyclicUtil(u, visited, -1))<br\/>                    return true;<br\/> <br\/>        return false;<br\/>    }<br\/> <br\/> <br\/>    \/\/ Driver method to test above methods<br\/>    public static void main(String args[])<br\/>    {<br\/>        \/\/ Create a graph given in the above diagram<br\/>        Graph g1 = new Graph(5);<br\/>        g1.addEdge(1, 0);<br\/>        g1.addEdge(0, 2);<br\/>        g1.addEdge(2, 0);<br\/>        g1.addEdge(0, 3);<br\/>        g1.addEdge(3, 4);<br\/>        if (g1.isCyclic())<br\/>            System.out.println(&quot;Graph contains cycle&quot;);<br\/>        else<br\/>            System.out.println(&quot;Graph doesn&#039;t contains cycle&quot;);<br\/> <br\/>        Graph g2 = new Graph(3);<br\/>        g2.addEdge(0, 1);<br\/>        g2.addEdge(1, 2);<br\/>        if (g2.isCyclic())<br\/>            System.out.println(&quot;Graph contains cycle&quot;);<br\/>        else<br\/>            System.out.println(&quot;Graph doesn&#039;t contains cycle&quot;);<br\/>    }<br\/>}<br\/>\/\/ This code is contributed by Aakash Hasija<\/code><\/pre> <\/div>\n<h3 id=\"output\"><span style=\"color: #000080;\"><strong>Output:<\/strong><\/span><\/h3>\n<pre>Graph contains cycle\r\nGraph doesn't contain cycle<\/pre>\n<p><span style=\"color: #993366;\"><strong>Time Complexity:<\/strong> <\/span>The program does a simple<strong> DFS Traversal of graph<\/strong> and graph is represented using adjacency list. So the time complexity is <strong>O(V+E)<\/strong><\/p>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Java Algorithm &#8211; Detect cycle in an undirected graph &#8211; Graph Algorithms &#8211; Given an undirected graph, how to check if there is a cycle in the graph<\/p>\n","protected":false},"author":1,"featured_media":31290,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1,74168,73906,2139],"tags":[76186,76526,76185,76184,76189,76183,76187,76525],"class_list":["post-25992","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-coding","category-dfs-and-bfs","category-graph-algorithms","category-java","tag-detect-cycle-in-directed-graph-c","tag-detect-cycle-in-directed-graph-dfs","tag-detect-cycle-in-directed-graph-in-c","tag-detect-cycle-in-directed-graph-java","tag-detect-cycle-in-graph-using-bfs","tag-detect-cycle-in-undirected-graph","tag-detect-cycle-in-undirected-graph-in-c","tag-detect-cycle-in-undirected-graph-java"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25992","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=25992"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25992\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media\/31290"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=25992"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=25992"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=25992"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}