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.



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
The following graph is not Eulerian since there are four vertices with an odd in-degree (0, 2, 3, 5).
Non-Eulerian Graph

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
For example, the following graph has an Eulerian cycle since every vertex has an even degree.
Eulerian Cycle

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
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

Download   Run Code

The time complexity of the above solution is O(n+m) where n is a number of vertices and m is a number of edges in the graph. Depending upon how dense the graph is, the number of edges m may vary between O(1) and O(n2).

source