Given a directed graph, check if it is possible to construct a cycle that visits each edge exactly once, i.e., check whether the graph has an Eulerian cycle or not.

Practice this problem

Related Post:

Check whether an undirected graph is Eulerian

 
An Eulerian trail (or Eulerian path) is a path that visits every edge in a graph exactly once. An Eulerian circuit (or Eulerian cycle) is an Eulerian trail that starts and ends on the same vertex. A directed graph has an Eulerian cycle if and only if

  1. Every vertex has equal in-degree and out-degree, and
  2. All of its vertices with a non-zero degree belong to a single strongly connected component.

The graph is strongly connected if it contains a directed path from u to v and a directed path from v to u for every pair of vertices (u, v). For example, the following graph has an Eulerian cycle [0 -> 1 -> 2 -> 3 -> 1 -> 4 -> 3 -> 0] since it is strongly connected, and each vertex has an equal in-degree and out-degree:

Eulerian cycle in a directed graph

 
Following is the implementation in C++, Java, and Python to check whether a given directed graph has an Eulerian cycle using Kosaraju’s algorithm to find the strongly connected component in the graph.

C++


Download  Run Code

Output:

The graph has an Eulerian cycle

Java


Download  Run Code

Output:

The graph has an Eulerian cycle

Python


Download  Run Code

Output:

The graph has an Eulerian cycle

The time complexity of the above solution is the same as that of Kosaraju’s algorithm, i.e., O(V + E), where V and E are the total number of vertices and edges in the graph, respectively.