[LeetCode]207. Course Schedule

  • descrption
    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:
    1.The input prerequisites is a graph represented by a list of edges, not adjacency matrices.
    2.You may assume that there are no duplicate edges in the input prerequisites.

  • 解题思路
    这道题是很明显的有关拓扑排序的题目,我们把每个课程当作一个node,提前需要学习的课程node用边指向学习它后才能学习这门课的课程node,如果图中有环,那么证明无法学习完所有的课程。这样问题就可以转换为一个图是否是一个有向无环图。首先我们根据给定的课程总数目和课程对(pair)构造图,遍历存储课程对的vector,记录每个节点的入度,记录从每个节点出去的边。之后遍历每个节点,如果该节点入度为0,那么删去这个节点,并且将这个节点指向的节点的入度减一,重复上述操作直至所有节点都被删除或者找不到入度为0的节点停止,如果所有节点都被删除那么这个图就是有向无环图,如果找不到入度为0的节点但还有节点没有被删除,那么这个图中就有环,这样课程就不能学习完。

  • 代码如下

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

        if(numCourses == 0)
            return false;
        //记录每个节点的入度和从该节点发出的边
        vector<int> indegree(numCourses, 0);
        unordered_map<int, multiset<int>> edges;

        for(auto node : prerequisites){
            indegree[node.second]++;
            edges[node.first].insert(node.second);
        }

    //遍历每个节点,找到入度为0的节点删除,并将指向节点的入度减1
        for(int i = 0, j; i < numCourses; i++){
            for(j = 0; j < numCourses; j++)
                if(indegree[j] == 0)
                    break;
            if(j == numCourses)
                return false;
            indegree[j] --;
            for(auto edge : edges[j]){
                     indegree[edge]--;
            }
        }
        return true;
    }
};

原题地址
如有错误请指正,谢谢!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值