{"id":27168,"date":"2018-01-03T22:01:13","date_gmt":"2018-01-03T16:31:13","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27168"},"modified":"2018-10-31T14:40:18","modified_gmt":"2018-10-31T09:10:18","slug":"python-programming-eulerian-path-circuit-undirected-graph","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/python-programming-eulerian-path-circuit-undirected-graph\/","title":{"rendered":"Eulerian path and circuit for undirected graph"},"content":{"rendered":"<p>Eulerian Circuit is an Eulerian Path which starts and ends on the same vertex.<\/p>\n<h3 id=\"how-to-find-whether-a-given-graph-is-eulerian-or-not\"><span style=\"color: #ff0000;\"><strong>How to find whether a given graph is Eulerian or not?<\/strong><\/span><\/h3>\n<p>The problem is same as following question. \u201cIs it possible to draw a given <a href=\"https:\/\/www.wikitechy.com\/technology\/python-programming-check-graph-strongly-connected-set-1-kosaraju-using-dfs\/\" target=\"_blank\" rel=\"noopener\">graph<\/a> without lifting pencil from the paper and without tracing any of the edges more than once\u201d.<\/p>\n<p>A graph is called Eulerian if it has an Eulerian Cycle and called Semi-Eulerian if it has an Eulerian Path. The problem seems similar to <a href=\"https:\/\/www.wikitechy.com\/technology\/backtracking-set-6-hamiltonian-cycle\/\" target=\"_blank\" rel=\"noopener\">Hamiltonian Path<\/a>\u00a0which is NP complete problem for a general graph. Fortunately, we can find whether a given graph has a Eulerian Path or not in polynomial time. In fact, we can find it in <strong>O(V+E)<\/strong> time.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p>Following are some interesting properties of undirected graphs with an Eulerian path and cycle. We can use these properties to find whether a graph is Eulerian or not.<\/p>\n<h3 id=\"eulerian-cycle\"><span style=\"color: #003300;\"><strong>Eulerian Cycle<\/strong><\/span><\/h3>\n<p>An <a href=\"https:\/\/www.wikitechy.com\/technology\/detect-cycle-undirected-graph\/\" target=\"_blank\" rel=\"noopener\">undirected graph<\/a> has Eulerian cycle if following two conditions are true.<br \/>\n\u2026.a) All vertices with non-zero degree are connected. We don\u2019t care about vertices with zero degree because they don\u2019t belong to Eulerian Cycle or Path (we only consider all edges).<br \/>\n\u2026.b) All vertices have even degree.<\/p>\n<h3 id=\"eulerian-path\"><span style=\"color: #003300;\"><strong>Eulerian Path<\/strong><\/span><\/h3>\n<p>An undirected graph has Eulerian Path if following two conditions are true.<br \/>\n\u2026.a) Same as condition (a) for Eulerian Cycle<br \/>\n\u2026.b) If zero or two vertices have odd degree and all other vertices have even degree. Note that only one vertex with odd degree is not possible in an undirected graph (sum of all degrees is always even in an undirected graph)<\/p>\n<p>Note that a graph with no edges is considered Eulerian because there are no edges to traverse.<\/p>\n<h3 id=\"how-does-this-work\"><span style=\"color: #800000;\"><strong>How does this work?<\/strong><\/span><\/h3>\n<p>In Eulerian path, each time we visit a vertex v, we walk through two unvisited edges with one end point as v. Therefore, all middle vertices in Eulerian Path must have even degree. For Eulerian Cycle, any vertex can be middle vertex, therefore all vertices must have even degree.<\/p>\n[ad type=&#8221;banner&#8221;]\n<h3 id=\"python-programming\"><span style=\"color: #003366;\">PYTHON Programming:<\/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 check if a given graph is Eulerian or not<br\/>#Complexity : O(V+E)<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\/>    # function to add an edge to graph<br\/>    def addEdge(self,u,v):<br\/>        self.graph[u].append(v)<br\/>        self.graph[v].append(u)<br\/>  <br\/>    #A function used by isConnected<br\/>    def DFSUtil(self,v,visited):<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 visited[i]==False:<br\/>                self.DFSUtil(i,visited)<br\/>  <br\/>  <br\/>    &#039;&#039;&#039;Method to check if all non-zero degree vertices are<br\/>    connected. It mainly does DFS traversal starting from <br\/>    node with non-zero degree&#039;&#039;&#039;<br\/>    def isConnected(self):<br\/>  <br\/>        # Mark all the vertices as not visited<br\/>        visited =[False]*(self.V)<br\/> <br\/>        #  Find a vertex with non-zero degree<br\/>        for i in range(self.V):<br\/>            if len(self.graph[i]) &gt; 1:<br\/>                break<br\/> <br\/>        # If there are no edges in the graph, return true<br\/>        if i == self.V-1:<br\/>            return True<br\/> <br\/>        # Start DFS traversal from a vertex with non-zero degree<br\/>        self.DFSUtil(i,visited)<br\/> <br\/>        # Check if all non-zero degree vertices are visited<br\/>        for i in range(self.V):<br\/>            if visited[i]==False and len(self.graph[i]) &gt; 0:<br\/>                return False<br\/>         <br\/>        return True<br\/> <br\/> <br\/>    &#039;&#039;&#039;The function returns one of the following values<br\/>       0 --&gt; If grpah is not Eulerian<br\/>       1 --&gt; If graph has an Euler path (Semi-Eulerian)<br\/>       2 --&gt; If graph has an Euler Circuit (Eulerian)  &#039;&#039;&#039;<br\/>    def isEulerian(self):<br\/>        # Check if all non-zero degree vertices are connected<br\/>        if self.isConnected() == False:<br\/>            return 0<br\/>        else:<br\/>            #Count vertices with odd degree<br\/>            odd = 0<br\/>            for i in range(self.V):<br\/>                if len(self.graph[i]) % 2 !=0:<br\/>                    odd +=1<br\/> <br\/>            &#039;&#039;&#039;If odd count is 2, then semi-eulerian.<br\/>            If odd count is 0, then eulerian<br\/>            If count is more than 2, then graph is not Eulerian<br\/>            Note that odd count can never be 1 for undirected graph&#039;&#039;&#039;<br\/>            if odd == 0:<br\/>                return 2<br\/>            elif odd == 2:<br\/>                return 1<br\/>            elif odd &gt; 2:<br\/>                return 0<br\/> <br\/> <br\/>    # Function to run test cases<br\/>    def test(self):<br\/>        res = self.isEulerian()<br\/>        if res == 0:<br\/>            print &quot;graph is not Eulerian&quot;<br\/>        elif res ==1 :<br\/>            print &quot;graph has a Euler path&quot;<br\/>        else:<br\/>            print &quot;graph has a Euler cycle&quot;<br\/>  <br\/>  <br\/> <br\/>#Let us create and test graphs shown in above figures<br\/>g1 = Graph(5);<br\/>g1.addEdge(1, 0)<br\/>g1.addEdge(0, 2)<br\/>g1.addEdge(2, 1)<br\/>g1.addEdge(0, 3)<br\/>g1.addEdge(3, 4)<br\/>g1.test()<br\/> <br\/>g2 = Graph(5)<br\/>g2.addEdge(1, 0)<br\/>g2.addEdge(0, 2)<br\/>g2.addEdge(2, 1)<br\/>g2.addEdge(0, 3)<br\/>g2.addEdge(3, 4)<br\/>g2.addEdge(4, 0)<br\/>g2.test();<br\/> <br\/>g3 = Graph(5)<br\/>g3.addEdge(1, 0)<br\/>g3.addEdge(0, 2)<br\/>g3.addEdge(2, 1)<br\/>g3.addEdge(0, 3)<br\/>g3.addEdge(3, 4)<br\/>g3.addEdge(1, 3)<br\/>g3.test()<br\/> <br\/>#Let us create a graph with 3 vertices<br\/># connected in the form of cycle<br\/>g4 = Graph(3)<br\/>g4.addEdge(0, 1)<br\/>g4.addEdge(1, 2)<br\/>g4.addEdge(2, 0)<br\/>g4.test()<br\/> <br\/># Let us create a graph with all veritces<br\/># with zero degree<br\/>g5 = Graph(3)<br\/>g5.test()<\/code><\/pre> <\/div>\n<h3 id=\"output\"><span style=\"color: #008000;\">Output:<\/span><\/h3>\n<pre>graph has a Euler path\r\ngraph has a Euler cycle\r\ngraph is not Eulerian\r\ngraph has a Euler cycle\r\ngraph has a Euler cycle<\/pre>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>PYTHON Programming &#8211; Eulerian path and circuit for undirected graph &#8211; Eulerian Path is a path in graph that visits every edge exactly once.<\/p>\n","protected":false},"author":1,"featured_media":31259,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1,78385,73906,4148],"tags":[80980,80982,80979,80983,73926,80984,80981,80985],"class_list":["post-27168","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-coding","category-connectivity","category-graph-algorithms","category-python","tag-euler-tour-geeks-for-geeks","tag-eulerian-graph-example","tag-eulerian-path-directed-graph","tag-fleurys-algorithm","tag-hamiltonian-circuit","tag-hierholzer-algorithm-c","tag-how-to-print-a-eulerian-path-or-circuit","tag-semi-eulerian-graph"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27168","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=27168"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27168\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media\/31259"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27168"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27168"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27168"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}