LintCode 616. Course Schedule II

题目

这里写图片描述

思路

拓扑排序,BFS,记录下来遍历的顺序即可。

代码

class Solution:
    """
    @param: numCourses: a total of n courses
    @param: prerequisites: a list of prerequisite pairs
    @return: the course order
    """
    def getCourseDict(self, prerequisites):
        course_dict = {}
        for course in prerequisites:
            if course[1] in course_dict:
                course_dict[course[1]].append(course[0])
            else:
                course_dict[course[1]] =[]
                course_dict[course[1]].append(course[0])
        return course_dict
    def getPreCourseNum(self, prerequisites):
        pre_course_num_dict = {}
        for course in prerequisites:
            if course[0] in pre_course_num_dict:
                pre_course_num_dict[course[0]] += 1
            else:
                pre_course_num_dict[course[0]] = 1
        return pre_course_num_dict
    def getStartCourse(self, pre_course_num_dict, n):
        start_course_list = []
        for i in range(n):
            if i not in pre_course_num_dict:
                start_course_list.append(i)
        return start_course_list
    def bfs(self, course_dict, pre_course_num_dict, start_course_list):
        res_list = []
        queue = []
        for course in start_course_list:
            queue.append(course)
        while queue:
            course = queue[0]
            queue.pop(0)
            res_list.append(course)
            if course in course_dict:
                for next_course in course_dict[course]:
                    pre_course_num_dict[next_course] -= 1
                    if pre_course_num_dict[next_course] == 0:
                        queue.append(next_course)
        for val in pre_course_num_dict.values():
            if val:
                return []
        return res_list
    def findOrder(self, numCourses, prerequisites):
        # write your code here
        if not numCourses: return []
        course_dict = self.getCourseDict(prerequisites)
        pre_course_num_dict = self.getPreCourseNum(prerequisites)
        start_course_list = self.getStartCourse(pre_course_num_dict, numCourses)
        if not start_course_list: return []
        return self.bfs(course_dict, pre_course_num_dict, start_course_list)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值