{"id":27649,"date":"2018-04-09T20:17:31","date_gmt":"2018-04-09T14:47:31","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27649"},"modified":"2018-09-16T13:19:06","modified_gmt":"2018-09-16T07:49:06","slug":"fleurys-algorithm-printing-eulerian-path-circuit","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/fleurys-algorithm-printing-eulerian-path-circuit\/","title":{"rendered":"PYTHON programming Fleury\u2019s Algorithm for printing Eulerian Path or Circuit"},"content":{"rendered":"<p><a href=\"http:\/\/en.wikipedia.org\/wiki\/Eulerian_path\" target=\"_blank\" rel=\"noopener noreferrer\">Eulerian Path\u00a0<\/a>is a path in graph that visits every edge exactly once. Eulerian Circuit is an Eulerian Path which starts and ends on the same vertex.<span id=\"more-121669\"><\/span><\/p>\n<p>We strongly recommend to first read the following post on Euler Path and Circuit.<br \/>\n<a href=\"http:\/\/www.geeksforgeeks.org\/eulerian-path-and-circuit\/\" target=\"_blank\" rel=\"noopener noreferrer\">http:\/\/www.geeksforgeeks.org\/eulerian-path-and-circuit\/<\/a><\/p>\n<p>In the above mentioned post, we discussed the problem of finding out whether a given graph is Eulerian or not. In this post, an algorithm to print Eulerian trail or circuit is discussed.<\/p>\n<p>Following is Fleury\u2019s Algorithm for printing Eulerian trail or cycle (Source <a href=\"http:\/\/www.math.ku.edu\/~jmartin\/courses\/math105-F11\/Lectures\/chapter5-part2.pdf\" target=\"_blank\" rel=\"noopener noreferrer\">Ref1<\/a>).<\/p>\n<p><strong>1.<\/strong> Make sure the graph has either 0 or 2 odd vertices.<\/p>\n<p><strong>2.<\/strong> If there are 0 odd vertices, start anywhere. If there are 2 odd vertices, start at one of them.<\/p>\n<p><strong>3. <\/strong>Follow edges one at a time. If you have a choice between a bridge and a non-bridge, <em>always choose the non-bridge<\/em>.<\/p>\n<p><strong>4.<\/strong> Stop when you run out of edges.<\/p>\n<p>The idea is, <strong><em>\u201cdon\u2019t burn <a href=\"http:\/\/www.geeksforgeeks.org\/bridge-in-a-graph\/\" target=\"_blank\" rel=\"noopener noreferrer\">bridges<\/a>\u201c<\/em><\/strong> so that we can come back to a vertex and traverse remaining edges. For example let us consider the following graph.<\/p>\n<p>There are two vertices with odd degree, \u20182\u2019 and \u20183\u2019, we can start path from any of them. Let us start tour from vertex \u20182\u2019.<\/p>\n<p>There are three edges going out from vertex \u20182\u2019, which one to pick? We don\u2019t pick the edge \u20182-3\u2019 because that is a bridge (we won\u2019t be able to come back to \u20183\u2019). We can pick any of the remaining two edge. Let us say we pick \u20182-0\u2019. We remove this edge and move to vertex \u20180\u2019.<\/p>\n<p>There is only one edge from vertex \u20180\u2019, so we pick it, remove it and move to vertex \u20181\u2019. Euler tour becomes \u20182-0 0-1\u2019.<\/p>\n<p>There is only one edge from vertex \u20181\u2019, so we pick it, remove it and move to vertex \u20182\u2019. Euler tour becomes \u20182-0 0-1 1-2\u2019<\/p>\n<p>Again there is only one edge from vertex 2, so we pick it, remove it and move to vertex 3. Euler tour becomes \u20182-0 0-1 1-2 2-3\u2019<\/p>\n<p>There are no more edges left, so we stop here. Final tour is \u20182-0 0-1 1-2 2-3\u2019.<\/p>\n<p>See <a href=\"http:\/\/www.math.ku.edu\/~jmartin\/courses\/math105-F11\/Lectures\/chapter5-part2.pdf\" target=\"_blank\" rel=\"noopener noreferrer\">this <\/a>for and <a href=\"http:\/\/www.austincc.edu\/powens\/+Topics\/HTML\/05-6\/05-6.html\" target=\"_blank\" rel=\"noopener\">this <\/a>fore more examples.<\/p>\n<p>Following is C++ implementation of above algorithm. In the following code, it is assumed that the given graph has an Eulerian trail or Circuit. The main focus is to print an Eulerian trail or circuit. We can use <a href=\"http:\/\/www.geeksforgeeks.org\/eulerian-path-and-circuit\/\" target=\"_blank\" rel=\"noopener noreferrer\">isEulerian()<\/a> to first check whether there is an Eulerian Trail or Circuit in the given graph.<\/p>\n<p>We first find the starting point which must be an odd vertex (if there are odd vertices) and store it in variable \u2018u\u2019. If there are zero odd vertices, we start from vertex \u20180\u2019. We call printEulerUtil() to print Euler tour starting with u. We traverse all adjacent vertices of u, if there is only one adjacent vertex, we immediately consider it. If there are more than one adjacent vertices, we consider an adjacent v only if edge u-v is not a bridge. How to find if a given is edge is bridge? We count number of vertices reachable from u. We remove edge u-v and again count number of reachable vertices from u. If number of reachable vertices are reduced, then edge u-v is a bridge. To count reachable vertices, we can either use BFS or DFS, we have used DFS in the above code. The function DFSCount(u) returns number of vertices reachable from u.<br \/>\nOnce an edge is processed (included in Euler tour), we remove it from the graph. To remove the edge, we replace the vertex entry with -1 in adjacency list. Note that simply deleting the node may not work as the code is recursive and a parent call may be in middle of adjacency list.<\/p>\n<p>PYTHON PROGRAMMING:<\/p>\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 print Eulerian Trail in a given Eulerian or Semi-Eulerian Graph<br\/>  <br\/>from collections import defaultdict<br\/>  <br\/>#This class represents an 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\/>        self.Time = 0<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\/>    # This function removes edge u-v from graph <br\/>    def rmvEdge(self, u, v):<br\/>        for index, key in enumerate(self.graph[u]):<br\/>            if key == v:<br\/>                self.graph[u].pop(index)<br\/>        for index, key in enumerate(self.graph[v]):<br\/>            if key == u:<br\/>                self.graph[v].pop(index)<br\/> <br\/>    # A DFS based function to count reachable vertices from v<br\/>    def DFSCount(self, v, visited):<br\/>        count = 1<br\/>        visited[v] = True<br\/>        for i in self.graph[v]:<br\/>            if visited[i] == False:<br\/>                count = count + self.DFSCount(i, visited)        <br\/>        return count<br\/> <br\/>    # The function to check if edge u-v can be considered as next edge in<br\/>    # Euler Tour<br\/>    def isValidNextEdge(self, u, v):<br\/>        # The edge u-v is valid in one of the following two cases:<br\/>  <br\/>        #  1) If v is the only adjacent vertex of u<br\/>        if len(self.graph[u]) == 1:<br\/>            return True<br\/>        else:<br\/>            &#039;&#039;&#039;<br\/>             2) If there are multiple adjacents, then u-v is not a bridge<br\/>                Do following steps to check if u-v is a bridge<br\/>  <br\/>            2.a) count of vertices reachable from u&#039;&#039;&#039; <br\/>            visited =[False]*(self.V)<br\/>            count1 = self.DFSCount(u, visited)<br\/> <br\/>            &#039;&#039;&#039;2.b) Remove edge (u, v) and after removing the edge, count<br\/>                vertices reachable from u&#039;&#039;&#039;<br\/>            self.rmvEdge(u, v)<br\/>            visited =[False]*(self.V)<br\/>            count2 = self.DFSCount(u, visited)<br\/> <br\/>            #2.c) Add the edge back to the graph<br\/>            self.addEdge(u,v)<br\/> <br\/>            # 2.d) If count1 is greater, then edge (u, v) is a bridge<br\/>            return False if count1 &gt; count2 else True<br\/> <br\/> <br\/>    # Print Euler tour starting from vertex u<br\/>    def printEulerUtil(self, u):<br\/>        #Recur for all the vertices adjacent to this vertex<br\/>        for v in self.graph[u]:<br\/>            #If edge u-v is not removed and it&#039;s a a valid next edge<br\/>            if self.isValidNextEdge(u, v):<br\/>                print(&quot;%d-%d &quot; %(u,v)),<br\/>                self.rmvEdge(u, v)<br\/>                self.printEulerUtil(v)<br\/> <br\/> <br\/>     <br\/>    &#039;&#039;&#039;The main function that print Eulerian Trail. It first finds an odd<br\/>   degree vertex (if there is any) and then calls printEulerUtil()<br\/>   to print the path &#039;&#039;&#039;<br\/>    def printEulerTour(self):<br\/>        #Find a vertex with odd degree<br\/>        u = 0<br\/>        for i in range(self.V):<br\/>            if len(self.graph[i]) %2 != 0 :<br\/>                u = i<br\/>                break<br\/>        # Print tour starting from odd vertex<br\/>        print (&quot;\\n&quot;)<br\/>        self.printEulerUtil(u)<br\/> <br\/># Create a graph given in the above diagram<br\/> <br\/>g1 = Graph(4)<br\/>g1.addEdge(0, 1)<br\/>g1.addEdge(0, 2)<br\/>g1.addEdge(1, 2)<br\/>g1.addEdge(2, 3)<br\/>g1.printEulerTour()<br\/> <br\/> <br\/>g2 = Graph(3)<br\/>g2.addEdge(0, 1)<br\/>g2.addEdge(1, 2)<br\/>g2.addEdge(2, 0)<br\/>g2.printEulerTour()<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(3, 2)<br\/>g3.addEdge(3, 1)<br\/>g3.addEdge(2, 4)<br\/>g3.printEulerTour()<br\/> <\/code><\/pre> <\/div>\n<p>Output:<\/p>\n<pre>2-0  0-1  1-2  2-3\r\n0-1  1-2  2-0\r\n0-1  1-2  2-0  0-3  3-4  4-2  2-3  3-1<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>PYTHON programming Fleury\u2019s Algorithm for printing Eulerian Path or Circuit &#8211;  learn in 30 sec from microsoft awarded MVP,Eulerian Path is a path in graph that visits every edge exactly once. <\/p>\n","protected":false},"author":1,"featured_media":31282,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[78385,73906],"tags":[80980,80979,81883,81880,81882,80984,81881,81879],"class_list":["post-27649","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-connectivity","category-graph-algorithms","tag-euler-tour-geeks-for-geeks","tag-eulerian-path-directed-graph","tag-fleurys-algorithm-complexity","tag-fleurys-algorithm-definition","tag-fleurys-algorithm-proof","tag-hierholzer-algorithm-c","tag-hierholzer-algorithm-implementation","tag-what-is-fleurys-algorithm"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27649","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=27649"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27649\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media\/31282"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27649"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27649"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27649"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}