Advertisement
Guest User

Untitled

a guest
Mar 26th, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.00 KB | None | 0 0
  1. class Solution {
  2. public:
  3. vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
  4. vector<vector<int>> graph(numCourses, vector<int>());
  5. vector<int> inDegree(numCourses); // 入度为 0 时顶点可以删除
  6. vector<int> res;
  7. queue<int> q; // 存储入度为 0 的顶点
  8. int cnt = 0; // 放入 res 的元素个数
  9.  
  10. for(auto &p : prerequisites) {
  11. graph[p.second].push_back(p.first);
  12. inDegree[p.first]++;
  13. }
  14.  
  15. for(int i = 0; i < numCourses; i++)
  16. if(inDegree[i] == 0)
  17. q.push(i);
  18.  
  19. while(!q.empty()){
  20. int cur = q.front();
  21. q.pop();
  22.  
  23. res.push_back(cur);
  24. cnt++;
  25.  
  26. for(auto j : graph[cur]){
  27. inDegree[j]--;
  28. if(inDegree[j] == 0)
  29. q.push(j);
  30. }
  31. }
  32.  
  33. if(cnt < numCourses) {
  34. return vector<int>();
  35. }
  36. return res;
  37. }
  38. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement