leetcode210 - course schedule II - medium

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] .

思路:这题是用visit来判断是否是个环,如果是个环,那么意味着不能上完课。用graph把所有和某一门课有关的其他课都存储进来,graph[i].append(j).
class Solution:
    def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
        if not numCourses and not prerequisites: return []
    
        
        graph = [[] for _ in range(numCourses)]
        visit = [0] * (numCourses)
        
        for j, i in prerequisites:
            graph[i].append(j)
        res = []  
        for i in range(numCourses):
            if not self.dfs(i, graph, visit, res):
                return []
        return res[::-1]
    
    
    def dfs(self, i, graph,visit, res):
        if visit[i] == -1:
            return False
        if visit[i] == 1:
            return True
        visit[i] = -1
        for j in graph[i]:
            if not self.dfs(j, graph, visit, res):
                return False
        res.append(i)
        visit[i] = 1
        return True
 

猜你喜欢

转载自www.cnblogs.com/sky37/p/11588137.html