LeetCode 207. Course Schedule

简介: 现在你总共有 n 门课需要选,记为 0 到 n-1。在选修某些课程之前需要一些先修课程。 例如,想要学习课程 0 ,你需要先完成课程 1 ,我们用一个匹配来表示他们: [0,1]给定课程总量以及它们的先决条件,判断是否可能完成所有课程的学习?

v2-9c812845746c5637fd0be088bcaf2e11_1440w.jpg

Description



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?


Example 1:

Input: 2,[[1,0]]

Output: true

Explanation: There are a total of 2 courses to take.

To take course 1 you should have finished course 0. So it is possible.


Example 2:

Input: 2, [[1,0],[0,1]]

Output: false


Explanation: 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.


描述



现在你总共有 n 门课需要选,记为 0 到 n-1。

在选修某些课程之前需要一些先修课程。 例如,想要学习课程 0 ,你需要先完成课程 1 ,我们用一个匹配来表示他们: [0,1]

给定课程总量以及它们的先决条件,判断是否可能完成所有课程的学习?


示例 1:

输入: 2, [[1,0]]

输出: true

解释: 总共有 2 门课程。学习课程 1 之前,你需要完成课程 0。所以这是可能的。


示例 2:

输入: 2, [[1,0],[0,1]]

输出: false

解释: 总共有 2 门课程。学习课程 1 之前,你需要先完成课程 0;并且学习课程 0 之前,你还应先完成课程 1。这是不可能的。


思路



  • 本题考察图,本题使用广度优先搜索.
  • 我们构建一个字典,值为当前课程,值为数组,list中包含当前课程结束接着可以上的课程.
  • 我们维护一个数组,数组中的值为数组索引所对应课程需要多少个前驱课程,如list[4]=7,表示要上4号课程,之前要上节课程.
  • 我们使用一个队列进行深度右边遍历,先遍历入度为0的课程,每次遍历一个课程就将该课程的下一个课程入度减一,同时检查下一个课程是否被减到了0,若是则将其添加到队列尾,进行下一次遍历.最后我们检查所有课程的入度,如果所有的课程入度都为0,说明所有的课程都已经上完,若不是则说明还有课程无法上完,我们返回False.


# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2019-01-21 12:05:36
# @Last Modified by:   何睿
# @Last Modified time: 2019-01-21 20:26:27
from collections import deque
class Solution:
    def canFinish(self, numCourses, prerequisites):
        """
        :type numCourses: int
        :type prerequisites: List[List[int]]
        :rtype: bool
        """
        if not numCourses: return 0
        nextcourse, indegree = {}, [0] * numCourses
        # 构建字典,键为课程,值为上完编号为键的课可以上的下一节课
        for item in prerequisites:
            if item[1] not in nextcourse:
                nextcourse[item[1]] = [item[0]]
            else:
                nextcourse[item[1]].append(item[0])
            # 统计每一个课程的入度
            indegree[item[0]] += 1
        # 统计入度为0的课程
        queue = deque()
        for i in range(numCourses):
            if not indegree[i]: queue.append(i)
        # 只要有入度为0的课程就继续循环
        while queue:
            c = queue.popleft()
            # 下一次将要上的课程
            for _next in nextcourse.get(c, []):
                # 当前课程已经上了,下一节课入度减一
                indegree[_next] -= 1
                # 将新产生的入度为0的课程添加到队列中
                if not indegree[_next]: queue.append(_next)
        for item in indegree:
            if item: return False
        return True

源代码文件在这里.


目录
相关文章
[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.
1086 0
LeetCode - 207. Course Schedule
207. Course Schedule  Problem's Link  ---------------------------------------------------------------------------- Mean:  给定一个有向图,判断是否存在top_sort序列.
987 0
[LeetCode] Course Schedule
As suggested by the hints, this problem is equivalent to detecting a cycle in the graph represented by prerequisites.
868 0
[LeetCode] Course Schedule II
Well, this problem is spiritually similar to to Course Schedule. You only need to store the nodes in the order you visit into a vector during BFS or DFS.
693 0
|
1月前
|
Python
【Leetcode刷题Python】剑指 Offer 32 - III. 从上到下打印二叉树 III
本文介绍了两种Python实现方法,用于按照之字形顺序打印二叉树的层次遍历结果,实现了在奇数层正序、偶数层反序打印节点的功能。
41 6
|
1月前
|
Python
【Leetcode刷题Python】剑指 Offer 26. 树的子结构
这篇文章提供了解决LeetCode上"剑指Offer 26. 树的子结构"问题的Python代码实现和解析,判断一棵树B是否是另一棵树A的子结构。
35 4
|
1月前
|
搜索推荐 索引 Python
【Leetcode刷题Python】牛客. 数组中未出现的最小正整数
本文介绍了牛客网题目"数组中未出现的最小正整数"的解法,提供了一种满足O(n)时间复杂度和O(1)空间复杂度要求的原地排序算法,并给出了Python实现代码。
73 2
|
1月前
|
索引 Python
【Leetcode刷题Python】从列表list中创建一颗二叉树
本文介绍了如何使用Python递归函数从列表中创建二叉树,其中每个节点的左右子节点索引分别是当前节点索引的2倍加1和2倍加2。
35 7