拓扑排序:课程表Course Schedule

给定课程总数和预修课对,判断能否完成所有课程。例如,当有2门课程,课程1依赖课程0时,可以完成;但如果课程1依赖课程0,同时课程0又依赖课程1,则无法完成。这个问题涉及到有向图的环检测和拓扑排序。拓扑排序是通过维护一个入度为0的节点队列,每次弹出节点并更新其可达节点的入度,如果所有节点的入度最终都能变为0,说明图中没有环,存在拓扑排序。
摘要由CSDN通过智能技术生成

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


};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值