Eulerian Path
An Eulerian path (欧拉路径; 一笔画问题) is a path visiting every edge exactly once.
Any connected directed graph where all nodes have equal in-degree and out-degree has an Eulerian circuit (an Eulerian path ending where it started.)
If the end point is the same as the starting point, this Eulerian Path is called an Eulerian Circuit (欧拉回路).
Detecting Eulerian Path
Undirected Graph:
If there are only TWO nodes with odd degrees and all other nodes have even degrees, then there must exist an Eulerian Path (NOT Circuit) from one of the odd-degree node to the other odd-degree node.
If all nodes have even degrees, this Eulerian Path is also a Eulerian Circuit.
Directioned Graph:
If there is at most one node
u
whoseoutdegree[u] = indegree[u] + 1
, and at most one nodev
whoseindegree[v] = outdegree[v] + 1
, then there must exists an Eulerian Path fromu
(Ifu
doesn't exist, any node works) tov
(Ifv
doesn't exist, any node works).If every nodes
n
hasindegree[n] = outdegree[n]
, then there is an Eulerian Circuit.
Finding Eulerian Circuit: Hierholzer’s Algorithm
Hierholzer’s Algorithm for directed graph
We can find the circuit/path in O(E)
, i.e. linear time.
The algorithem is as follows (wiki):
Choose any starting vertex
v
, and follow a trail of edges from that vertex until returning tov
. It is not possible to get stuck at any vertex other thanv
, because the even degree of all vertices ensures that, when the trail enters another vertexw
there must be an unused edge leavingw
. The tour formed in this way is a closed tour, but may not cover all the vertices and edges of the initial graph.As long as there exists a vertex
u
that belongs to the current tour but that has adjacent edges not part of the tour, start another trail fromu
, following unused edges until returning tou
, and join the tour formed in this way to the previous tour.Since we assume the original graph is connected, repeating the previous step will exhaust all edges of the graph.
This is a Post-order DFS.
The following code is for 2097. Valid Arrangement of Pairs (Hard)
Problems
Last updated