Eulerian path and circuit for directed graph

Assume SCC

Eulerian Path is a path in graph that visits every edge exactly once. Eulerian Circuit is an Eulerian Path which starts and ends on the same vertex.

A graph is said to be eulerian if it has a eulerian cycle. We have discussed eulerian circuit for an undirected graph. In this post, the same is discussed for a directed graph.

For example, the following graph has eulerian cycle as {1, 0, 3, 4, 0, 2, 1}

class Solution {
    public static boolean isCircuit(List<Integer>[] graph) {
        int[] indegree = new int[graph.length];
        int[] outdegree = new int[graph.length];
        for (int i = 0; i < graph.length; i++) {
            for (int x : graph[i]) {
                indegree[x]++;
                outdegree[i]++;
            }
        }
        boolean smallerIndegreeFound = false;
        boolean biggerIndegreeFound = false;
        for (int i = 0; i < graph.length; i++) {
            if (indegree[i] != outdegree[i]) {
                if (indegree[i] + 1 == outdegree[i] && !biggerIndegreeFound)
                    biggerIndegreeFound = true;
                else if (outdegree[i] + 1 == indegree[i] && !smallerIndegreeFound)
                    smallerIndegreeFound = true;
                else
                    return false;
            }
        }
        if ((!smallerIndegreeFound && !biggerIndegreeFound) || (smallerIndegreeFound && biggerIndegreeFound))
            return true;
        return false;
    }

    public static boolean isPath(List<Integer>[] graph) {
        int[] indegree = new int[graph.length];
        int[] outdegree = new int[graph.length];
        for (int i = 0; i < graph.length; i++) {
            for (int x : graph[i]) {
                indegree[x]++;
                outdegree[i]++;
            }
        }
        for (int i = 0; i < graph.length; i++) {
            if (indegree[i] != outdegree[i])
                return false;
        }
        return true;
    }
}

Last updated