#include <bits/stdc++.h>
using namespace std;

class Solution
{
public:
    bool canFinish(int numCourses, vector<vector<int>> &prerequisites)
    {

        vector<vector<int>> graph(numCourses, vector<int>());

        for (auto num : prerequisites)
        {
            graph[num[1]].push_back(num[0]);
        }
        vector<int> visit(numCourses);

        for (int i = 0; i < numCourses; i++)
        {
            if (!dfs(graph, visit, i))
                return false;
        }
        return true;
    }
    bool dfs(vector<vector<int>> &g, vector<int> &visit, int i)
    {
        if (visit[i] == -1)
            return false;
        if (visit[i] == 1)
            return true;
        visit[i] = -1;
        for (auto a : g[i])
        {
            if (!dfs(g, visit, a))
                return false;
        }
        visit[i] = 1;
        return true;
    }
};