210. Course Schedule II

https://leetcode.com/problems/course-schedule-ii/description/

class Solution {
public:
    vector<int> findOrder(int n, vector<pair<int, int>>& pres) {
        vector<int> res;    if (n < 1)  return res;
        
        vector<unordered_set<int>> v(n);
        vector<int> d(n, 0);                // in-degree of each node
        for (const auto& p : pres) {
            v[p.second].insert(p.first);
            d[p.first]++;
        }
        
        for (int k = 0; k < n; k++) {
            int cur = 0;   // find a v which indegree is 0, then we can delete it
            while (cur < n && d[cur] != 0) cur++;
            if (cur == n)   { return vector<int>(); }
            for (auto nb : v[cur])
                d[nb]--;
            res.push_back(cur);
            d[cur] = -1;
        }
        return res;
    }
};

猜你喜欢

转载自www.cnblogs.com/JTechRoad/p/9000650.html