leetcode 210. 课程表 II

210. 课程表 II

leetcode 210. 课程表 II_第1张图片

class Solution {
public:
    vector<int> ans;
    int top;
    bool hasCicle(vector<vector<int> >& graph, vector<int>& visited, int ind) {
        for(auto adj : graph[ind]) {
            if(visited[adj] == 1) return true;
            if(visited[adj] == -1) continue;
            visited[adj] = 1;
            if(hasCicle(graph, visited, adj)) return true;
            visited[adj] = -1;
        }
        ans[top--] = ind;
        return false;
    }
    vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
        ans = vector<int>(numCourses, 0);
        top = numCourses - 1;
        vector<vector<int> > graph(numCourses);
        vector<int> visited(numCourses, 0);
        for(auto p : prerequisites) graph[p[1]].push_back(p[0]);
        for(int ii = 0; ii < numCourses; ii++) {
            if(visited[ii]) continue;
            visited[ii] = 1;
            if(hasCicle(graph, visited, ii)) return {};
            visited[ii] = -1;
        }
        return ans;
    }
};

leetcode 210. 课程表 II_第2张图片

class Solution {
public:
    vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
        vector<int> ans;
        queue<int> Q;
        vector<vector<int> > graph(numCourses);
        vector<int> indegrees(numCourses, 0);
        for(auto p : prerequisites) {
            graph[p[1]].push_back(p[0]);
            indegrees[p[0]]++;
        }
        for(int ii = 0; ii < numCourses; ii++) {
            if(indegrees[ii] == 0) Q.push(ii);
        }
        while(!Q.empty() && numCourses) {
            int ind = Q.front();
            Q.pop();
            numCourses--;
            ans.push_back(ind);
            for(auto adj : graph[ind]) {
                indegrees[adj]--;
                if(indegrees[adj] == 0) Q.push(adj);
            }
        }
        if(numCourses) return {};
        return ans;
    }
};

你可能感兴趣的:(new,leetcode,leetcode,算法)