LeetCode210. Course Schedule II (思路及python解法)

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, return the ordering of courses you should take to finish all courses.

There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.

Example 1:

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

Explanation: There are a total of 2 courses to take. To take course 1 you should have finished   
             course 0. So the correct course order is [0,1] .

这个题思路和LeetCode207. Course Schedulehttps://blog.csdn.net/AIpush/article/details/103372810思路是一样的,只不过记录一下学习课程的顺序。

需要注意的就是如果不能所有课程全学,返回[]。

class Solution:
    def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
        
        forward = {i:set() for i in range(numCourses)}
        backward = collections.defaultdict(set)
        
        for i,j in prerequisites:
            forward[i].add(j)
            backward[j].add(i)
        
        queue = collections.deque([node for node in forward if len(forward[node])==0])
        final=list(queue.copy())
        
        while queue:
            node = queue.popleft()
            for bac in backward[node]:
                forward[bac].remove(node)
                if len(forward[bac])==0:
                    queue.append(bac)
                    final.append(bac)
            forward.pop(node)
        if len(final)==numCourses:
            return final
        return []

 

你可能感兴趣的:(Python,LeetCode)