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.

click to show more hints.

Hints:
  1. This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses.
  2. There are several ways to represent a graph. For example, the input prerequisites is a graph represented by a list of edges. Is this graph representation appropriate?
  3. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort.
  4. Topological sort could also be done via BFS.

这道课程清单的问题对于我们学生来说应该不陌生,因为我们在选课的时候经常会遇到想选某一门课程,发现选它之前必须先上了哪些课程,这道题给了很多提示,第一条就告诉我们了这道题的本质就是在有向图中检测环。 LeetCode中关于图的题很少,有向图的仅此一道,还有一道关于无向图的题是Clone Graph 无向图的复制。个人认为图这种数据结构相比于树啊,链表啊什么的要更为复杂一些,尤其是有向图,很麻烦。第二条提示是在讲如何来表示一个有向图,可以用边来表示,边是由两个端点组成的,用两个点来表示边。第三第四条提示揭示了此题有两种解法,DFS和BFS都可以解此题。我们先来看BFS的解法,我们定义二维数组graph来表示这个有向图,一位数组in来表示每个顶点的入度。我们开始先根据输入来建立这个有向图,并将入度数组也初始化好。然后我们定义一个queue变量,将所有入度为0的点放入队列中,然后开始遍历队列,从graph里遍历其连接的点,每到达一个新节点,将其入度减一,如果此时该点入度为0,则放入队列末尾。直到遍历完队列中所有的值,若此时还有节点的入度不为0,则说明环存在,返回false,反之则返回true。代码如下:

解法一

class Solution {
public:
    bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
        vector<vector<));
        vector<);
        for (auto a : prerequisites) {
            graph[a[]].push_back(a[]);
            ++]];
        }
        queue<int> q;
        ; i < numCourses; ++i) {
            ) q.push(i);
        }
        while (!q.empty()) {
            int t = q.front();
            q.pop();
            for (auto a : graph[t]) {
                --in[a];
                ) q.push(a);
            }
        }
        ; i < numCourses; ++i) {
            ) return false;
        }
        return true;
    }
};

下面我们来看DFS的解法,也需要建立有向图,还是用二维数组来建立,和BFS不同的是,我们像现在需要一个一维数组visit来记录访问状态,大体思路是,先建立好有向图,然后从第一个门课开始,找其可构成哪门课,暂时将当前课程标记为已访问,然后对新得到的课程调用DFS递归,直到出现新的课程已经访问过了,则返回false,没有冲突的话返回true,然后把标记为已访问的课程改为未访问。代码如下:

解法二

class Solution {
public:
    bool canFinish(int numCourses, vector<vector<int> >& prerequisites) {
        vector<vector<));
        vector<);
        for (auto a : prerequisites) {
            graph[a[]].push_back(a[]);
        }
        ; i < numCourses; ++i) {
            if (!canFinishDFS(graph, visit, i)) return false;
        }
        return true;
    }
    bool canFinishDFS(vector<vector<int> > &graph, vector<int> &visit, int i) {
        ) return false;
        ) return true;
        visit[i] = -;
        for (auto a : graph[i]) {
            if (!canFinishDFS(graph, visit, a)) return false;
        }
        visit[i] = ;
        return true;
    }
};

类似题目:

Minimum Height Trees

Course Schedule II

参考资料:

http://www.cnblogs.com/easonliu/p/4483437.html

https://leetcode.com/discuss/34741/python-20-lines-dfs-solution-sharing-with-explanation

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Course Schedule 课程清单的更多相关文章

  1. [LeetCode] Course Schedule II 课程清单之二

    There are a total of n courses you have to take, labeled from 0 to n - 1. Some courses may have prer ...

  2. [LeetCode] Course Schedule III 课程清单之三

    There are n different online courses numbered from 1 to n. Each course has some duration(course leng ...

  3. LeetCode Course Schedule II

    原题链接在这里:https://leetcode.com/problems/course-schedule-ii/ 题目: There are a total of n courses you hav ...

  4. [LeetCode] Course Schedule I (207) &amp; II (210) 解题思路

    207. Course Schedule There are a total of n courses you have to take, labeled from 0 to n - 1. Some ...

  5. [Leetcode] Course Schedule

    There are a total of n courses you have to take, labeled from 0 to n - 1. Some courses may have prer ...

  6. [LeetCode] Minimum Height Trees 最小高度树

    For a undirected graph with tree characteristics, we can choose any node as the root. The result gra ...

  7. [CareerCup] 4.2 Route between Two Nodes in Directed Graph 有向图中两点的路径

    4.2 Given a directed graph, design an algorithm to find out whether there is a route between two nod ...

  8. leetcode题目清单

    2016-09-24,开始刷leetcode上的算法题,下面整理一下leetcode题目清单.Github-leetcode 1.基本数学 Two Sum Palindrome Number Cont ...

  9. Java for LeetCode 210 Course Schedule II

    There are a total of n courses you have to take, labeled from 0 to n - 1. Some courses may have prer ...

随机推荐

  1. 敏捷遇上UML—软创基地马年大会(广州站 2014-4-19)

        我们将在广州为您奉献高端知识大餐,当敏捷遇上UML,会发生怎样的化学作用呢?首席专家张老师将会为您分享需求分析及软件设计方面的最佳实践,帮助您掌握敏捷.UML及两者相结合的实战技巧. 时间:2 ...

  2. DEV控件中GridView中的复选框与CheckBox实现联动的全选功能

    最初的界面图如图1-1(全选框ID: cb_checkall  DEV控件名称:gcCon ): 要实现的功能如下图(1-2  1-3  1-4)及代码所示: 图1-2 图1-3 图1-4 O(∩_∩ ...

  3. 全面解析sizeof(上) 分类: C/C++ StudyNotes 2015-06-15 10:18 188人阅读 评论(0) 收藏

    以下代码使用平台是Windows7 64bits+VS2012. sizeof是C/C++中的一个操作符(operator),其作用就是返回一个对象或者类型所占的内存字节数,使用频繁,有必须对齐有个全 ...

  4. KO中对象数组排序时,两个属性的优先顺序不一致时的排序实现

    function FromSort(left, right, asc) {    if (left.属性1 != "") {        if (right.属性1 != &qu ...

  5. JPEG格式

    Jpg文件格式[参考] 微处理机中的存放顺序有正序(big endian)和逆序(little endian)之分.正序存放就是高字节存放在前低字节在后,而逆序存放就是低字节在前高字节在后.例如,十六 ...

  6. 原生JavaScript技巧大收集(11~20)-(终于又被我找到这篇文章了)

    11.原生JavaScript加入收藏夹 function AddFavorite(sURL, sTitle) { try { window.external.addFavorite(sURL, sT ...

  7. Mongo聚合函数

    { "_id" : ObjectId("57301c7e5fd5d6e2afa221d1"), "a" : "张三", ...

  8. HDU-4405 Aeroplane chess(概率DP求期望)

    题目大意:一个跳棋游戏,每置一次骰子前进相应的步数.但是有的点可以不用置骰子直接前进,求置骰子次数的平均值. 题目分析:状态很容易定义:dp(i)表示在第 i 个点出发需要置骰子的次数平均值.则状态转 ...

  9. 条款24:若所有的函数参数可能都需要发生类型转换才能使用,请采用non-member函数

    假设有一个有理数类Rational,有一个计算有理数乘法的成员函数operator*,示例如下: #include <iostream> class Rational { public: ...

  10. uva 11294

    Problem E: Wedding Up to thirty couples will attend a wedding feast, at which they will be seated on ...