{"id":25988,"date":"2017-10-26T09:25:55","date_gmt":"2017-10-26T03:55:55","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=25988"},"modified":"2018-10-30T15:38:29","modified_gmt":"2018-10-30T10:08:29","slug":"python-algorithm-detect-cycle-undirected-graph","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/python-algorithm-detect-cycle-undirected-graph\/","title":{"rendered":"Detect cycle in an undirected graph"},"content":{"rendered":"<h3 id=\"python-algorithm-detect-cycle-in-an-undirected-graph\"><span style=\"color: #003366;\"><strong>Python Algorithm: detect cycle in an undirected graph:<\/strong><\/span><\/h3>\n<p>Given an <a href=\"https:\/\/www.wikitechy.com\/technology\/detect-cycle-undirected-graph\/\" target=\"_blank\" rel=\"noopener\">undirected graph<\/a>, how to check if there is a cycle in the graph? For example, the following graph has a cycle 1-0-2-1.<\/p>\n<p>We have discussed cycle detection for directed graph. We have also discussed a <a href=\"https:\/\/www.wikitechy.com\/technology\/25974-2\/\" target=\"_blank\" rel=\"noopener\">union-find algorithm for cycle detection in undirected graphs<\/a>. The time complexity of the union-find algorithm is <strong>O(ELogV)<\/strong>. Like directed graphs, we can use DFS to detect cycle in an undirected graph in <strong>O(V+E)<\/strong> time. We do a <a href=\"https:\/\/www.wikitechy.com\/technology\/python-algorithm-depth-first-traversal-dfs-graph\/\" target=\"_blank\" rel=\"noopener\">DFS traversal<\/a> of the given graph. For every visited vertex \u2018<strong>v<\/strong>\u2019, if there is an adjacent \u2018<strong>u<\/strong>\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<h3 id=\"python-programming-to-detect-cycle-in-an-undirected-graph\"><span style=\"color: #003366;\"><strong>Python Programming to detect cycle in an undirected graph:<\/strong><\/span><\/h3>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-python code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-python code-embed-code\"># Python Program to detect cycle in an undirected graph<br\/> <br\/>from collections import defaultdict<br\/>  <br\/>#This class represents a undirected graph using adjacency list representation<br\/>class Graph:<br\/>  <br\/>    def __init__(self,vertices):<br\/>        self.V= vertices #No. of vertices<br\/>        self.graph = defaultdict(list) # default dictionary to store graph<br\/> <br\/>  <br\/>    # function to add an edge to graph<br\/>    def addEdge(self,v,w):<br\/>        self.graph[v].append(w) #Add w to v_s list<br\/>        self.graph[w].append(v) #Add v to w_s list<br\/>  <br\/>    # A recursive function that uses visited[] and parent to detect<br\/>    # cycle in subgraph reachable from vertex v.<br\/>    def isCyclicUtil(self,v,visited,parent):<br\/> <br\/>        #Mark the current node as visited <br\/>        visited[v]= True<br\/> <br\/>        #Recur for all the vertices adjacent to this vertex<br\/>        for i in self.graph[v]:<br\/>            # If the node is not visited then recurse on it<br\/>            if  visited[i]==False : <br\/>                if(self.isCyclicUtil(i,visited,v)):<br\/>                    return True<br\/>            # If an adjacent vertex is visited and not parent of current vertex,<br\/>            # then there is a cycle<br\/>            elif  parent!=i:<br\/>                return True<br\/>         <br\/>        return False<br\/>         <br\/>  <br\/>    #Returns true if the graph contains a cycle, else false.<br\/>    def isCyclic(self):<br\/>        # Mark all the vertices as not visited<br\/>        visited =[False]*(self.V)<br\/>        # Call the recursive helper function to detect cycle in different<br\/>        #DFS trees<br\/>        for i in range(self.V):<br\/>            if visited[i] ==False: #Don&#039;t recur for u if it is already visited<br\/>                if(self.isCyclicUtil(i,visited,-1))== True:<br\/>                    return True<br\/>         <br\/>        return False<br\/> <br\/># Create a graph given in the above diagram<br\/>g = Graph(5)<br\/>g.addEdge(1, 0)<br\/>g.addEdge(0, 2)<br\/>g.addEdge(2, 0)<br\/>g.addEdge(0, 3)<br\/>g.addEdge(3, 4)<br\/> <br\/>if g.isCyclic():<br\/>    print &quot;Graph contains cycle&quot;<br\/>else :<br\/>    print &quot;Graph does not contain cycle &quot;<br\/>g1 = Graph(3)<br\/>g1.addEdge(0,1)<br\/>g1.addEdge(1,2)<br\/> <br\/> <br\/>if g1.isCyclic():<br\/>    print &quot;Graph contains cycle&quot;<br\/>else :<br\/>    print &quot;Graph does not contain cycle &quot;<br\/>  <br\/>#This code is contributed by Neelam Yadav<\/code><\/pre> <\/div>\n<h3 id=\"output\"><span style=\"color: #008000;\"><strong>Output:<\/strong><\/span><\/h3>\n<pre>Graph contains cycle\r\nGraph doesn't contain cycle<\/pre>\n<p><span style=\"color: #3366ff;\"><strong>Time Complexity:<\/strong> <\/span>The program does a simple DFS Traversal of graph and <a href=\"https:\/\/www.wikitechy.com\/technology\/python-programming-check-graph-strongly-connected-set-1-kosaraju-using-dfs\/\" target=\"_blank\" rel=\"noopener\">graph<\/a> 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>Python 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,4148],"tags":[76523,76185,76184,76187,76525,76190,76522,76524],"class_list":["post-25988","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-coding","category-dfs-and-bfs","category-graph-algorithms","category-python","tag-cycle-in-directed-graph","tag-detect-cycle-in-directed-graph-in-c","tag-detect-cycle-in-directed-graph-java","tag-detect-cycle-in-undirected-graph-in-c","tag-detect-cycle-in-undirected-graph-java","tag-find-all-cycles-in-a-directed-graph","tag-find-all-cycles-in-an-undirected-graph","tag-find-cycle-in-undirected-graph"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25988","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=25988"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25988\/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=25988"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=25988"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=25988"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}