Eulerian Path & Circuit
In 1736, the city of Königsberg had seven bridges connecting its islands. A local puzzle asked: can you walk through the city crossing every bridge exactly once and return home?
Leonhard Euler proved it was impossible — and in doing so, invented graph theory. The key insight he found still works today: you can solve the puzzle by looking only at how many bridges touch each landmass.
The Two Questions
An Eulerian circuit starts and ends at the same spot, using every edge exactly once (like coming home after crossing all bridges). An Eulerian path uses every edge exactly once but can end somewhere different from where it started.
The Magic Degree Condition (Undirected Graphs)
Every time you enter a vertex through one bridge, you need another bridge to leave — unless it's the very start or end. This means:
- Eulerian circuit exists ↔ graph is connected and every vertex has even degree.
- Eulerian path exists ↔ graph is connected and exactly two vertices have odd degree (those are the start and end).
Königsberg had four landmasses, all with odd degree — so neither a circuit nor a path was possible. Euler saw this in seconds.
Directed Graphs
For directed graphs, replace "even degree" with balanced in/out-degree: an Eulerian circuit needs every vertex to have in-degree = out-degree. An Eulerian path needs exactly one vertex with out-degree = in-degree + 1 (start) and one with in-degree = out-degree + 1 (end).
Hierholzer's Algorithm: Building the Route
Checking existence is trivial — actually building the route takes a bit more cleverness. Hierholzer's method works like this:
- Start anywhere and greedily follow edges (marking them used) until you're stuck — this gives you a circuit, but it might skip some edges.
- Find any vertex on your circuit that still has unused edges. Start a new mini-circuit from there.
- Splice the mini-circuit into the main circuit at that vertex's position.
- Repeat until no unused edges remain.
With the right data structure (a doubly-linked list), each splice is \(O(1)\), giving \(O(V+E)\) overall.