[LeetCode]207. Course Schedule

来源:互联网 发布:matlab gui 编程实例 编辑:程序博客网 时间:2024/05/21 10:56
  • 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;    }};

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

原创粉丝点击