[LeetCode] 207. Course Schedule/Course Schedule II @ python

一.题目:
告诉你要修多少门课程,以及这些课程之间的关系,问最终是否能修完所有课程.
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.

二.解题思路:
首先我们可以根据课程之间的关系建立一张图.然后找到所有入度为0的节点(这门课程肯定能修)放入队列.然后,每次排出一个队列元素,首先把它对应的入度列表元素值置为-1,将其邻近的图节点入度-1,若满足节点入度为0则放入队列,最后判断入度列表中是否存在没有更改的元素.
代码如下:

class Solution(object):
    def canFinish(self, numCourses, prerequisites):
        """
        :type numCourses: int
        :type prerequisites: List[List[int]]
        :rtype: bool
        """
        graph = collections.defaultdict(list)
        indegrees = [0] * numCourses
        for i in prerequisites:
            graph[i[1]].append(i[0])
            indegrees[i[0]] += 1
        queue = collections.deque()
        for i in range(numCourses):
            if indegrees[i] == 0:
                queue.append(i)
        
        while queue:
            tmp = queue.pop()
            indegrees[tmp] = -1
            for j in graph[tmp]:
                indegrees[j] -=1
                if indegrees[j] == 0:
                    queue.append(j)
        
        for i in indegrees:
            if i != -1:
                return False
        return True

对于第二题,只需要添加一个result收集每次队列排出的元素即可.
代码如下:

class Solution(object):
    def findOrder(self, numCourses, prerequisites):
        """
        :type numCourses: int
        :type prerequisites: List[List[int]]
        :rtype: List[int]
        """
        graph = collections.defaultdict(list)
        indegrees = [0] * numCourses
        result = []
        for i in prerequisites:
            graph[i[1]].append(i[0])
            indegrees[i[0]] += 1
        queue = collections.deque()
        for i in range(numCourses):
            if indegrees[i] == 0:
                queue.append(i)
        
        while queue:
            tmp = queue.pop()
            result.append(tmp)
            indegrees[tmp] = -1
            for j in graph[tmp]:
                indegrees[j] -=1
                if indegrees[j] == 0:
                    queue.append(j)
        
        for i in indegrees:
            if i != -1:
                return []
        return result
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值