知之可否

Be yourself; everyone else is already taken.​

拓扑排序:课程表Course Schedule

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;
    }


};
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/gao1440156051/article/details/51546892
个人分类: leetcode
想对作者说点什么? 我来说一句

拓扑排序 ---排课表----数据结构

2010年06月13日 414KB 下载

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭