Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- vector<unordered_set<int>> make_graph(int numCourses, vector<vector<int>> &prerequisites){
- vector<unordered_set<int>> myGraph(numCourses);
- for(auto &x: prerequisites){
- myGraph[x[1]].insert(x[0]);
- }
- return myGraph;
- }
- bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
- vector<unordered_set<int>> myGraph = make_graph(numCourses, prerequisites);
- vector<int> inDegrees(numCourses);
- for(auto &x: myGraph){
- for(auto &y: x){
- inDegrees[y]++;
- }
- }
- queue<int> q;
- int c = 0;
- for(int i=0; i<inDegrees.size(); i++){
- if(inDegrees[i]==0){
- c++;
- q.push(i);
- }
- }
- while(!q.empty()){
- //currently queue contains all the nodes with indegree of zero
- //we have to pop them and update the neighbors indegrees and push them accordingly
- int qSize = q.size();
- while(qSize--){
- int fr = q.front();
- q.pop();
- for(auto &x: myGraph[fr]){
- inDegrees[x]--;
- if(inDegrees[x]==0){
- c++;
- q.push(x);
- }
- }
- }
- }
- //c is the count of the nodes which have final Indegree as 0
- return (c==numCourses);
- }
- };
Add Comment
Please, Sign In to add comment