LeetCode 207、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:

  1. The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
  2. You may assume that there are no duplicate edges in the input prerequisites

题解

     本题等价于有向图是否有环,显然使用拓扑排序的思想即可求解。

    拓扑排序的思想为:

  (1)从有向图中选取一个入度为0的顶点,输出或保存;

  (2)从有向图中删去此顶点以及所有以它为起点的边;

   重复上述步骤,直至图空;若图不空,存在环。

    这里需要解释一下入度的概念。一个顶点的度是指与该顶点相关联的边的条数,对于有向图来说,一个顶点的度可细分为入度和出度。一个顶点的入度是指与其关联的各边之中,以其为终点的边数;出度则是相对的概念,指以该顶点为起点的边数。

代码

    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
        int nSize = prerequisites.size();
        if (nSize == 0)
            return true;
        
        vector<int> nIndegree(numCourses, 0);
        vector<vector<int>> Graph(numCourses);
        queue<int> sources;
        for (int i = 0; i < nSize; i++) {
            nIndegree[prerequisites[i].first]++;  //求入度
            Graph[prerequisites[i].second].push_back(prerequisites[i].first); //边
        }
        for (int i = 0; i < numCourses; i++) {
            if (nIndegree[i] == 0)
                sources.push(i);
        }
        
        int nTotal = 0;
        while (!sources.empty()) {
            int nTmp = sources.front();
            sources.pop();
            int nEdges = Graph[nTmp].size();
            for (int i = 0; i < nEdges; i++) {
                nIndegree[Graph[nTmp][i]]--;
                if (nIndegree[Graph[nTmp][i]] == 0)
                    sources.push(Graph[nTmp][i]);
            }
            nTotal++;
        }
        
        if (nTotal == numCourses)
            return true;
        else
            return false;
    }
      LeetCode 210、Course Schedule II与本题的思路是一致的,区别只在于本题不需要保存拓扑排序的序列,而LeetCode 210需要。
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值