Topological Sort

DFS:

class Solution {
public:
    vector<int> res;
    bool detectedCycle = false;
    vector<int> findOrder(int n, vector<pair<int, int>>& pres) {
        if (n < 1)  return res;
        
        vector<unordered_set<int>> v(n);
        for (const auto& p : pres)
            v[p.second].insert(p.first);
        
        vector<int> visited(n, -1);
        for (int i = 0; i < n; i++)
            dfs(v, visited, i);
        
        reverse(res.begin(), res.end());            // result in reverse order
        return detectedCycle ? vector<int>() : res;
    }
    void dfs(vector<unordered_set<int>>& v, vector<int>& visited, int n) {
        if (detectedCycle || visited[n] != -1)  return;
        visited[n] = 1;
        for (int i : v[n]) {
            if (visited[i] == 1)
                detectedCycle = true;
            else if (visited[i] == 2)
                continue;
            else
                dfs(v, visited, i);
        }
        visited[n] = 2;
        res.push_back(n);       // push current node to the end, and final result is in reverse order.
    }
};

Topological sort:

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;
    }
};
原文地址:https://www.cnblogs.com/JTechRoad/p/9001333.html