207. Course Schedule 拓扑排序

207. Course Schedule 拓扑排序_第1张图片
image.png

邻接表:vector>
队列,将入度为0的顶点添加到队列里,然后拿出队首顶点,将它指向的点的入度减一,直到最后所有的点都入过队列,则证明没有环。

拓扑排序的bfs解法

class Solution {
public:
    bool canFinish(int numCourses, vector>& prerequisites) {
        vector> edges(numCourses, vector ());
        vector in_degree(numCourses, 0);
        queue q;
        for(int i = 0; i < prerequisites.size(); i++){
            edges[prerequisites[i].first].push_back(prerequisites[i].second);
            in_degree[prerequisites[i].second]++;
        }
        for(int i = 0; i < numCourses; i++){
            if(in_degree[i] == 0)
                q.push(i);
        }
        int res = 0;
        while(q.size()){
            int cur = q.front();
            q.pop();
            res++;
            for(int  i = 0; i < edges[cur].size(); i++){
                in_degree[edges[cur][i]]--;
                if(in_degree[edges[cur][i]] == 0)
                    q.push(edges[cur][i]);
            }
        }
        return res == numCourses;
    }
};

第二种:210. Course Schedule II


207. Course Schedule 拓扑排序_第2张图片
image.png

输出拓扑序:

class Solution {
public:
    vector findOrder(int numCourses, vector>& prerequisites) {
        vector res;
        vector> edges(numCourses, vector ());
        vector in_degree(numCourses, 0);
        queue q;
        for(int i = 0; i < prerequisites.size(); i++){
            edges[prerequisites[i].first].push_back(prerequisites[i].second);
            in_degree[prerequisites[i].second]++;
        }
        for(int i = 0; i < numCourses; i++){
            if(in_degree[i] == 0)
                q.push(i);
        }
        while(q.size()){
            int cur = q.front();
            q.pop();
            res.insert(res.begin(),cur);//注意vector的insert(),是要迭代器
            for(int  i = 0; i < edges[cur].size(); i++){
                in_degree[edges[cur][i]]--;
                if(in_degree[edges[cur][i]] == 0)
                    q.push(edges[cur][i]);
            }
        }
        if(res.size() == numCourses) return res;
        else{
            return vector ();
        }       
    }
};

你可能感兴趣的:(207. Course Schedule 拓扑排序)