关闭

拓扑排序:课程表Course Schedule

556人阅读 评论(0) 收藏 举报
分类:

There are a total of n courses you have to take, labeled from 0 to n - 1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?

For example:

2, [[1,0]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.

2, [[1,0],[0,1]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.

Note:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.

有向图中是否有环。

拓扑排序
用一个队列维护所有入度为0的节点,每次弹出一个节点v,查看从v可达的所有节点u;
将u的入读减一,若u的入度此时为0, 则将u加入队列。
在队列为空时,检查所有节点的入度,若所有节点入度都为0, 则存在这样的一个拓扑排序 —— 有向图中不存在环。

class Solution {
public:
    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {

        vector<int> inDgree(numCourses,0);
        map<int, vector<int> >adjNode;

        int len = prerequisites.size();
        for (int i = 0; i < len; i++){
            pair<int, int> p = prerequisites[i];

            if (find(adjNode[p.second].begin(), adjNode[p.second].end(), p.first) == adjNode[p.second].end()){
                adjNode[p.second].push_back(p.first);
                inDgree[p.first]++;
            }
        }

        queue<int> Q;

        for (int i=0; i < numCourses; i++){
            if (inDgree[i] == 0)
                Q.push(i);
        }

        while (!Q.empty()){
            int front = Q.front();
            Q.pop();

            vector<int> adj = adjNode[front];

            for (int i:adj){
                inDgree[i]--;
                if (inDgree[i] == 0){
                    Q.push(i);
                }
            }

        }

        for (int i: inDgree){
            if (i)
                return false;
        }
        return true;
    }


};
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:389701次
    • 积分:7975
    • 等级:
    • 排名:第2668名
    • 原创:390篇
    • 转载:276篇
    • 译文:0篇
    • 评论:27条
    联系方式
    E-mail:gwh_mail@qq.com QQ:1440156051
    最新评论