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. orcle form 传数据乱码

    在jsp顶部加入<%@ page contentType="text/html; charset=utf-8" language="java" impor ...

  2. bzoj4559: [JLoi2016]成绩比较

    感谢丁爷爷教我做这个题的后半部分. 首先,运用一发容斥原理,求出所有人与B神每门课分数相对关系的不同方案数. 这个似乎大(wo)家(lan)都(de)会(hui)了(yi),我就不说了,详见代码里的f ...

  3. Essential Documents to Manage Your Projects

    Speak to an experienced project manager, and they can give you a wealth of good advice on the do's a ...

  4. notpad++安装python插件

    1.安装python并添加到环境变量 2.在notpad++ 运行工具下点击运行,输入如下命令: cmd /k python "$(FULL_CURRENT_PATH)" & ...

  5. 2016年12月13日 星期二 --出埃及记 Exodus 21:8

    2016年12月13日 星期二 --出埃及记 Exodus 21:8 If she does not please the master who has selected her for himsel ...

  6. log4net按等级多种方式记录日志

    log4net.config <?xml version="1.0"?> <configuration> <configSections> &l ...

  7. Feister network

    在密码学中,Feister network(又叫Feister Function, 一下简称 F函数)是一种用在块加密上的对称结构,很多种块加密算法都是使用这种结构. 优点: 1.加解密的过程非常相似 ...

  8. Tkinter教程之Frame篇

    本文转载自:http://blog.csdn.net/jcodeer/article/details/1811339 '''Tkinter教程之Frame篇'''#Frame就是屏幕上的一块矩形区域, ...

  9. CF192div2-C - Purification

    题意: 从给定的图中找出某些点,这些点能够消除同一行和同一列的“怪物”.求使得最少的点的位置. 关键:要想消除整张的图的妖怪,必须选中n个点(对于n行n列来说)!!!!!!!!!!! 做法:对于每一行 ...

  10. 部分 CM11 系统 Android 平板执行植物大战僵尸 2 黑屏的解决的方法

    原文 http://forum.xda-developers.com/showthread.php?t=2755197 部分 CM11 系统的 Android 平板(比如三星 GT-P5110 )执行 ...