Eulerian Paths and Circuits
An Euler path uses every edge of a graph exactly once; an Euler circuit also ends where it started. Whether one exists depends only on vertex degrees and connectivity, and Hierholzer's algorithm finds it in O(E) by walking until stuck and splicing in detours.
Using Every Edge Exactly Once
An Euler path is a walk that uses every edge of the graph exactly once. It may pass through a vertex many times. If it also ends at the vertex where it began, it is an Eulerian circuit. A graph that has a circuit is called an eulerian graph; one that has a path but no circuit is sometimes called semi-Eulerian.
The question goes back to 1736 and the seven bridges of Königsberg: can you cross each bridge once and return home? Euler showed you cannot, and the reason was not the map but a count at each land mass. That count is still the whole test.
Covering every vertex once instead is the Hamiltonian cycle problem. It sounds similar but has no simple test and is NP-complete, while the Euler question is settled in linear time.
- Euler path: every edge once, any start and end
- Euler circuit: every edge once, back at the start
- Puzzles that ask you to draw a figure without lifting the pen are Euler path questions
The Degree Conditions
Each time a walk passes through a vertex it uses two edges there: one in, one out. So every vertex in the middle of the walk ends with an even number of used edges. Only the first and last vertex can be odd, and for a circuit they are the same vertex, so they are even too.
That gives the euler circuit conditions for an undirected graph: every vertex has even degree, and all edges belong to one connected piece. With exactly two odd vertices there is an Euler path, and it must start at one of them and end at the other. Exactly one odd vertex is impossible, because the degrees always add up to twice the number of edges. Four or more odd vertices rule out both; Königsberg has four.
For a directed graph, count in and out separately. A circuit needs in-degree = out-degree at every vertex. A path needs one vertex with one more out than in (the start), one with one more in than out (the end), and balance everywhere else. Connectivity is checked ignoring direction.
| Undirected graph | Directed graph | |
|---|---|---|
| Circuit | Every degree even | in = out at every vertex |
| Path, not circuit | Exactly two odd vertices; start at one | Start has out − in = 1, end has in − out = 1 |
| Always also | All edges in one connected piece | All edges in one piece, ignoring direction |
- Isolated vertices with no edges are ignored by the connectivity check
- A self-loop adds 2 to its vertex's degree, so it never changes parity
- Checking takes O(V + E): one pass for degrees, one search for connectivity
Hierholzer's Algorithm
- Push the start vertex (an odd vertex if there are two, any vertex with edges otherwise)
- Look at the top vertex. If it has an unused edge, mark the edge used and push the other end
- If it has none, pop it and append it to the tour
- Repeat until the stack is empty, then reverse the tour
- If the tour has fewer than E + 1 vertices, some edges were out of reach: no Euler tour
The conditions say a tour exists; Hierholzer's algorithm builds it. Walk from the start along unused edges until you get stuck. With even degrees you can only get stuck back at the start, because entering any other vertex leaves an odd number of unused edges there, at least one. If edges remain, some vertex on the walk still has unused ones: walk a detour from there, which also returns to where it began, and splice it in.
The stack version does the splicing for free. The tracer below runs it on a bowtie, two triangles sharing a vertex.
- Each edge is pushed once and each vertex popped once per visit: O(V + E) time
- Keep a pointer per vertex into its edge list, so used edges are not rescanned
- Mark undirected edges used by id, since each one appears in two lists
Terms, operations, and practical uses
Key terms
- DegreeNumber of edge ends at a vertex; a self-loop counts twice.
- Euler pathA walk that uses every edge exactly once.
- Eulerian circuitAn Euler path that ends where it started.
- SpliceInserting a closed detour into the tour at a vertex they share.
Related lessons and problems
- Hamiltonian CycleEvery vertex once instead of every edge.
- Graph Data StructuresDegrees, adjacency lists and edge ids.
- Articulation Points and BridgesThe bridges Fleury's algorithm avoids.
- Reconstruct Itinerary (problem)Hierholzer on a directed graph.
Code in Python, C++ and Java
def euler_tour(n, edges):
graph = [[] for _ in range(n)]
for i, (u, v) in enumerate(edges):
graph[u].append((v, i))
graph[v].append((u, i))
odd = [v for v in range(n) if len(graph[v]) % 2]
if len(odd) not in (0, 2):
return f"neither ({len(odd)} odd vertices)"
start = odd[0] if odd else next(v for v in range(n) if graph[v])
used = [False] * len(edges)
nxt = [0] * n
stack, tour = [start], []
while stack:
u = stack[-1]
while nxt[u] < len(graph[u]) and used[graph[u][nxt[u]][1]]:
nxt[u] += 1
if nxt[u] == len(graph[u]):
tour.append(stack.pop())
else:
v, i = graph[u][nxt[u]]
used[i] = True
stack.append(v)
if len(tour) != len(edges) + 1:
return "neither (edges in more than one piece)"
kind = "path" if odd else "circuit"
return kind + ": " + " ".join(map(str, reversed(tour)))
bowtie = [(0, 1), (1, 2), (2, 0), (2, 3), (3, 4), (4, 2)]
print("bowtie:", euler_tour(5, bowtie))
print("plus 0-3:", euler_tour(5, bowtie + [(0, 3)]))
print("plus 0-3, 1-4:", euler_tour(5, bowtie + [(0, 3), (1, 4)]))
print("two triangles:", euler_tour(6, [(0, 1), (1, 2), (2, 0), (3, 4), (4, 5), (5, 3)]))#include <iostream>
#include <string>
#include <utility>
#include <vector>
using namespace std;
string eulerTour(int n, const vector<pair<int, int>>& edges) {
vector<vector<pair<int, int>>> graph(n);
for (int i = 0; i < (int)edges.size(); i++) {
graph[edges[i].first].push_back({edges[i].second, i});
graph[edges[i].second].push_back({edges[i].first, i});
}
vector<int> odd;
for (int v = 0; v < n; v++)
if (graph[v].size() % 2) odd.push_back(v);
if (odd.size() != 0 && odd.size() != 2)
return "neither (" + to_string(odd.size()) + " odd vertices)";
int start = 0;
if (!odd.empty()) start = odd[0];
else while (graph[start].empty()) start++;
vector<bool> used(edges.size(), false);
vector<size_t> nxt(n, 0);
vector<int> stack = {start}, tour;
while (!stack.empty()) {
int u = stack.back();
while (nxt[u] < graph[u].size() && used[graph[u][nxt[u]].second]) nxt[u]++;
if (nxt[u] == graph[u].size()) {
tour.push_back(u);
stack.pop_back();
} else {
auto [v, i] = graph[u][nxt[u]];
used[i] = true;
stack.push_back(v);
}
}
if (tour.size() != edges.size() + 1) return "neither (edges in more than one piece)";
string out = odd.empty() ? "circuit:" : "path:";
for (auto it = tour.rbegin(); it != tour.rend(); ++it) out += " " + to_string(*it);
return out;
}
int main() {
vector<pair<int, int>> bowtie = {{0, 1}, {1, 2}, {2, 0}, {2, 3}, {3, 4}, {4, 2}};
cout << "bowtie: " << eulerTour(5, bowtie) << "\n";
auto one = bowtie;
one.push_back({0, 3});
cout << "plus 0-3: " << eulerTour(5, one) << "\n";
auto two = one;
two.push_back({1, 4});
cout << "plus 0-3, 1-4: " << eulerTour(5, two) << "\n";
cout << "two triangles: " << eulerTour(6, {{0, 1}, {1, 2}, {2, 0}, {3, 4}, {4, 5}, {5, 3}}) << "\n";
}import java.util.*;
public class Main {
static String eulerTour(int n, int[][] edges) {
List<List<int[]>> graph = new ArrayList<>();
for (int i = 0; i < n; i++) graph.add(new ArrayList<>());
for (int i = 0; i < edges.length; i++) {
graph.get(edges[i][0]).add(new int[]{edges[i][1], i});
graph.get(edges[i][1]).add(new int[]{edges[i][0], i});
}
List<Integer> odd = new ArrayList<>();
for (int v = 0; v < n; v++)
if (graph.get(v).size() % 2 == 1) odd.add(v);
if (odd.size() != 0 && odd.size() != 2) return "neither (" + odd.size() + " odd vertices)";
int start = 0;
if (!odd.isEmpty()) start = odd.get(0);
else while (graph.get(start).isEmpty()) start++;
boolean[] used = new boolean[edges.length];
int[] nxt = new int[n];
Deque<Integer> stack = new ArrayDeque<>();
List<Integer> tour = new ArrayList<>();
stack.push(start);
while (!stack.isEmpty()) {
int u = stack.peek();
List<int[]> adj = graph.get(u);
while (nxt[u] < adj.size() && used[adj.get(nxt[u])[1]]) nxt[u]++;
if (nxt[u] == adj.size()) {
tour.add(stack.pop());
} else {
int[] e = adj.get(nxt[u]);
used[e[1]] = true;
stack.push(e[0]);
}
}
if (tour.size() != edges.length + 1) return "neither (edges in more than one piece)";
StringBuilder sb = new StringBuilder(odd.isEmpty() ? "circuit:" : "path:");
for (int i = tour.size() - 1; i >= 0; i--) sb.append(" ").append(tour.get(i));
return sb.toString();
}
public static void main(String[] args) {
int[][] bowtie = {{0, 1}, {1, 2}, {2, 0}, {2, 3}, {3, 4}, {4, 2}};
System.out.println("bowtie: " + eulerTour(5, bowtie));
int[][] one = Arrays.copyOf(bowtie, 7);
one[6] = new int[]{0, 3};
System.out.println("plus 0-3: " + eulerTour(5, one));
int[][] two = Arrays.copyOf(one, 8);
two[7] = new int[]{1, 4};
System.out.println("plus 0-3, 1-4: " + eulerTour(5, two));
System.out.println("two triangles: " + eulerTour(6, new int[][]{{0, 1}, {1, 2}, {2, 0}, {3, 4}, {4, 5}, {5, 3}}));
}
}Step through it
Running on edges 0–1, 1–2, 2–0, 2–3, 3–4, 4–2
Why a Plain Walk Is Not Enough
Starting at a valid vertex and always taking any unused edge can strand you. On the bowtie, the walk 0 → 1 → 2 → 0 closes the first triangle and is stuck at 0 while three edges of the second triangle are untouched. Hierholzer's answer is to keep that walk and insert the missed loop at vertex 2.
The older Fleury's algorithm avoids getting stranded instead: at each step it refuses to cross a bridge (an edge whose removal cuts off unused edges) unless it has no other choice. It is correct but must test for bridges at every step, which costs O(E²) in a simple version, so Hierholzer is the one used in practice. Articulation points and bridges covers how bridges are found.
- Greedy walk: can strand edges
- Fleury: never burn a bridge, O(E²)
- Hierholzer: walk, then splice the missed loops, O(E)
Where Euler Tours Appear
Route inspection, also called the Chinese postman problem, asks for the shortest closed walk that covers every street. If all degrees are even the answer is an Euler circuit; otherwise the cheapest pairing of odd vertices is duplicated first. Snow ploughs, street sweepers and meter readers are scheduled this way.
Genome assemblers split reads into short overlapping pieces and build a de Bruijn graph, where the genome is an Euler path. The same graph gives a de Bruijn sequence, the shortest string containing every code of length k once, which is how a keypad that checks only the last k digits can be beaten in few presses.
- Reconstruct Itinerary: directed Euler path over flight tickets, smallest order first
- Drawing a figure in one stroke: check the number of odd vertices first
- Chinese postman and de Bruijn sequences: Euler circuits after a small fix to the graph