solution.cpp 881 字节
Newer Older
每日一练社区's avatar
每日一练社区 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
#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;
    }
};