Advertisement
spider68

course schedule

Jun 6th, 2021
637
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.73 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
  4.  
  5.         vector<int>id(numCourses),ans;
  6.         map<int,vector<int>>mp;
  7.         for(auto v:prerequisites){
  8.             id[v[0]]++;
  9.             mp[v[1]].push_back(v[0]);
  10.         }
  11.         queue<int>q;
  12.         for(int i=0;i<id.size();i++){
  13.             if(id[i]==0)q.push(i);
  14.         }
  15.         int cnt=0;
  16.         while(!q.empty()){
  17.             int x=q.front();
  18.             ans.push_back(x);
  19.             q.pop();
  20.             for(auto v:mp[x]){
  21.                 id[v]--;
  22.                 if(id[v]==0)q.push(v);
  23.             }
  24.             cnt++;
  25.         }
  26.         if(cnt!=numCourses)return {};
  27.         return ans;
  28.     }
  29. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement