Topological Sort

Posted The Tech Road

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
    }
};

 

以上是关于Topological Sort的主要内容,如果未能解决你的问题,请参考以下文章

Topological Sort

Topological Sort (25分)

6-16 Topological Sort(25 分)

Topological Sort

java 207.课程表(#Topological Sort).java

java 207.课程表(#Topological Sort).java