Given an undirected graph, check whether it has an Eulerian path or not. In other words, check if it is possible to construct a path that visits each edge exactly once.

Practice this problem

1. Eulerian trail (or Eulerian path, or Euler walk)

An Eulerian trail is a path that visits every edge in a graph exactly once. An undirected graph has an Eulerian trail if and only if

  1. Exactly zero or two vertices have odd degree, and
  2. All of its vertices with a non-zero degree belong to a single connected component.

The following graph is not Eulerian since four vertices have an odd in-degree (0, 2, 3, 5):

Non Eulerian Graph

2. Eulerian circuit (or Eulerian cycle, or Euler tour)

An Eulerian circuit is an Eulerian trail that starts and ends on the same vertex, i.e., the path is a cycle. An undirected graph has an Eulerian cycle if and only if

  1. Every vertex has an even degree, and
  2. All of its vertices with a non-zero degree belong to a single connected component.

For example, the following graph has an Eulerian cycle since every vertex has an even degree:

Eulerian Cycle

3. Semi–Eulerian

A graph that has an Eulerian trail but not an Eulerian circuit is called Semi–Eulerian. An undirected graph is Semi–Eulerian if and only if

  1. Exactly two vertices have odd degree, and
  2. All of its vertices with a non-zero degree belong to a single connected component.

The following graph is Semi–Eulerian since there are exactly two vertices with an odd in-degree (0, 1):

Semi-Eulerian Graph

 
The following implementation in C++, Java, and Python checks whether a given graph is Eulerian and contains an Eulerian cycle:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
The graph has an Eulerian path
The graph has an Eulerian cycle

The time complexity of the above solution is O(V × E), where V and E are the total number of vertices and edges in the graph, respectively. Depending upon how dense the graph is, the total number of edges E may vary between O(1) and O(V2).

 
Also See:

Eulerian cycle in directed graphs

 
References: Eulerian path – Wikipedia