Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
- vector<vector<int>> graph(numCourses, vector<int>());
- vector<int> inDegree(numCourses); // 入度为 0 时顶点可以删除
- vector<int> res;
- queue<int> q; // 存储入度为 0 的顶点
- int cnt = 0; // 放入 res 的元素个数
- for(auto &p : prerequisites) {
- graph[p.second].push_back(p.first);
- inDegree[p.first]++;
- }
- for(int i = 0; i < numCourses; i++)
- if(inDegree[i] == 0)
- q.push(i);
- while(!q.empty()){
- int cur = q.front();
- q.pop();
- res.push_back(cur);
- cnt++;
- for(auto j : graph[cur]){
- inDegree[j]--;
- if(inDegree[j] == 0)
- q.push(j);
- }
- }
- if(cnt < numCourses) {
- return vector<int>();
- }
- return res;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement