The below code shows the implementation of the Detect Cycle in a Directed Graph.

internal class Detect_Cycle_in_a_Directed_Graph
{
    Dictionary<int, List<int>> keyValuePairs = new Dictionary<int, List<int>>();
    bool explored = false;

    public void AddEdge(int v, int w)
    {
        keyValuePairs[v] = keyValuePairs.TryGetValue(v, out List<int> list) ? list : new List<int>();
        keyValuePairs[v].Add(w);
    }

    public bool IsCyclic()
    {
        bool[] visited = new bool[keyValuePairs.Count];
        for (int i = 0; i < keyValuePairs.Count; i++)
        {
            if (!visited[i])
            {
                IsCyclicUtil(i, keyValuePairs, visited);
                if (explored)
                    return true;
            }
        }
        return false;
    }

    void IsCyclicUtil(int src, Dictionary<int, List<int>> keyValuePairs, bool[] visited)
    {
        visited[src] = true;
        foreach (var value in keyValuePairs[src])
        {
            if (visited[value])
            {
                explored = true;
                return;
            }
            IsCyclicUtil(value, keyValuePairs, visited);
        }
    }
}

Time complexity: O(V + E).

Space Complexity: O(V + E)