Graphs/Euler Tour
From charlesreid1
Notes
An Euler tour of a graph G is a traversal of the graph (a walk) that visits each edge of the graph once.
This is not always possible to do - and, in fact, determining if an Euler tour of a graph exists is precisely the problem that led Euler to create the subject of graph theory in the first place. Euler was trying to tackle the Bridge of Königsberg problem, which was to determine if there is a walk through the different parts of Königsberg, connected by seven bridges, that requires the walker to cross each bridge exactly once.
Note that this is a special case of the First Theorem of Graph Theory, which states that the number of vertices with odd degree must be even. For a graph to be Eulerian, the number of vertices with odd degree must be 0 or 2.
A graph G on which an Euler tour is possible is said to be an Eulerian graph. A connected graph is Eulerian if and only if it has either 2 or 0 vertices of odd degree.
Pseudocode:
C = empty cycle at vertex 0 while G has unmarked edges: u = any vertex on C with unmarked edges C2 = empty list of edges v = u do: e = unmarked edge of v mark e append e to C2 v = other endpoint of e while v is not u Splice C2 into C at u end while
Fleury's Algorithm
v = v0 F = E C = trivial path at v[0] while G has unmarked edges if v has unmarked edge that is not a bridge of V,F then e = unmarked edge of v that is not a bridge of V,F else e = any unmarked edge of v mark e append e to C F = F - e v = other endpoint of e end
Using DFS
Euler tours can be found in directed graphs by using a depth-first search tree (see Graphs/DFS).
Start by constructing a DFS tree. Next, begin traversing the graph at the root of the DFS tree. Traverse the edges in reverse direction; any edge that leads back to the root node should be used last.
Related
Also see Tree Traversal/Traversal Method Template for a description of a template method pattern. This uses method hooks to re-use code that performs an Euler Tour on a tree.
Flags