a simplified c++ solution using topological sort


  • 0
    H
    class Solution {
    public:
        bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
            vector<int> indegree(numCourses, 0);
            vector<vector<int>> edges(numCourses);
            for(auto p : prerequisites) {
                int n1 = p.first, n2 = p.second;
                edges[n1].push_back(n2);
                indegree[n2] ++;
            }
            for(int i = 0; i < numCourses; i ++) {
                int j = 0;
                for(; j < numCourses; j ++)
                    if(indegree[j] == 0) break;
                if(j == numCourses) return false;
                indegree[j] = -1;
                for(int k : edges[j]) indegree[k] --;
            }
            return true;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.