Leetcode 210: Class Schedule II

Title description : Now you have a total of numCourses courses to choose, recorded as 0 to numCourses - 1. You are given an array prerequisites, where prerequisites[i] = [ai, bi], which means that you must take bi before taking course ai.

For example, if you want to study course 0, you need to complete course 1 first, we use a match to represent: [0,1].
Returns the sequence of studies you have placed in order to complete all courses. There may be more than one correct order, you just need to return any one. Returns an empty array if it is not possible to complete all courses.

Example :
Input: numCourses = 2, prerequisites = [[1,0]]
Output: [0,1]
Explanation: There are 2 courses in total. To study Lesson 1, you need to have completed Lesson 0 first. So the correct class order is [0,1].

Solution :
This question is almost the same as Leetcode 207. Class schedule. If you have done this in the past, just change the return value in your code from True/False to non-empty array/empty array.

class Solution:
    def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
        from collections import defaultdict
        from collections import deque#队列
         # 入度数组(列表,保存所有课程的依赖课程总数)
        in_degree_list = [0]*numCourses
        # 关系表,对应图中的邻接边(字典,保存所有课程与依赖课程的关系)
        #defaultdict(list),会构建一个默认value为list的字典
        relation_dict = defaultdict(list)
        for i in prerequisites:
            in_degree_list[i[0]] += 1
            #添加依赖它的后续课程
            #key为i[1],i[0]为value加到value列表中
            relation_dict[i[1]].append(i[0])
        queue = deque()
        for i in range(len(in_degree_list)):
            if in_degree_list[i] == 0:
                queue.append(i)
        ##准备工作完成
        ## 此时relations_list: {0: [3], 1: [3, 4], 2: [4], 3: [5], 4: [5]}
        ## queue: [0, 1, 2]        
        ##经典bfs 模版
        result = []
        while queue:
            current_zero_degree = queue.popleft()
            result.append(current_zero_degree)
            numCourses = numCourses - 1
            related_courses = relation_dict[current_zero_degree]
            if related_courses:
                for i in related_courses:
                    in_degree_list[i]-=1
                    if in_degree_list[i] == 0:
                        queue.append(i)
        return result if numCourses==0 else []

Guess you like

Origin blog.csdn.net/Rolandxxx/article/details/128865044