[LeetCode] 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.

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<int> > graph(numCourses, vector<int>(0));
        vector<int> in(numCourses, 0);
        for (auto a : prerequisites) {
            graph[a[1]].push_back(a[0]);
            ++in[a[0]];
        }
        queue<int> q;
        for (int i = 0; i < numCourses; ++i) {
            if (in[i] == 0) q.push(i);
        }
        while (!q.empty()) {
            int t = q.front();
            q.pop();
            for (auto a : graph[t]) {
                --in[a];
                if (in[a] == 0) q.push(a);
            }
        }
        for (int i = 0; i < numCourses; ++i) {
            if (in[i] != 0) return false;
        }
        return true;
    }
};

参考资料:

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

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

时间: 2024-10-14 11:20:58

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

[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 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 l

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

There are n different online courses numbered from 1 to n. Each course has some duration(course length) tand closed on dth day. A course should be taken continuously for t days and must be finished before or on the dth day. You will start at the 1st 

leetcode 207. Course Schedule 课程计划 ---------- java

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 l

LeetCode Course Schedule II

原题链接在这里:https://leetcode.com/problems/course-schedule-ii/ 是Course Schedule的进阶版题目.采用的是同一种方法,这里只需要返回一个结果,所以遍历过的节点放入array中即可. AC Java: 1 public class Solution { 2 public int[] findOrder(int numCourses, int[][] prerequisites) { 3 int [] res = new int[num

[LeetCode] Course Schedule

As suggested by the hints, this problem is equivalent to detecting a cycle in the graph represented by prerequisites. Both BFS and DFS can be used to solve this problem using the idea oftopological sort. If you find yourself unfamiliar with these con

课程清单

1.Week1(9月12日):很激动的第一次课 2.Week2(9月16日):动手做个简单的例子 3.Week2(9月19日):增加一个CodeFirst的例子来说明 4.Week3(9月23日):例子更Powerful更完整了,哇咔咔 5.Week3(9月26日):做完后,总结下

[LeetCode]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

《SAP微顾问和大数据 》公众号管理课程清单

互联网商业模式创新 电子商务与传统企业转型 “一带一路”信息化:格局与对策 “一带一路”沿线国家主权信用及风险防范 大数据下的资源整合和知识共享 地产数字化改革的痛点与处方 携手共建“一带一路” 数字经济与新实体经济 管理模式创新驱动新旧动能转换 中国企业股权激励现状分析及建议 “丝绸之路”起源和发展的中国视角 英国脱欧与欧盟未来 工业4.0与中国制造2025 互联网商业创新 战略管理的概念和基本框架(2)—公司战略与核心竞争力 战略管理的概念和基本框架(3)—公司战略与商业模式 战略管理的概念

[LeetCode] Minimum Height Trees 最小高度树

For a undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called minimum height trees (MHTs). Given such a graph, write