leetcode 课程表

class Solution {
public:
    bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
        int length = prerequisites.size();
        vector<int> c(numCourses, 0);
        vector<vector<int>> graph(numCourses);
        for(int i = 0; i <numCourses; i++)
            graph[i].resize(length);
        for(int i = 0; i < numCourses; i++)
        {
            int a = prerequisites[i][0];
            int b = prerequisites[i][1];
            graph[a][b] = 1;
        }
        for(int i = 0; i < numCourses; i++)
        {
            if(!c[i])
                if(!dfs(i, graph, c))
                    return false;
        }
        return true;
    }
    bool dfs(int i, vector<vector<int>>& v1, vector<int> &c)
    {
        #访问标志
        c[i] = -1;
        int n = v1.size();
        for(int j = 0; j < n; j++)
        {
             if(v1[i][j])
             {
                 if(c[j] < 0) return false;
                 else if(!c[j] && !dfs(j, v1, c)) return false;
             }
        }
        c[i] = 1;
        return true;
    }
};

你可能感兴趣的:(Leetcode,错题)