8/29/2020

[LeetCode] 210. Course Schedule II

Problem : https://leetcode.com/problems/course-schedule-ii/

Topological sort approach.


class Solution:
    def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
        graph = defaultdict(list)
        indegree = defaultdict(int)
        
        for course, pre in prerequisites:
            graph[pre].append(course)
            indegree[course] += 1
        
        
        noindegree = deque()
        
        for i in range(numCourses):
            if indegree[i] == 0:
                noindegree.append(i)
        
        result = []
        
        while noindegree:
            picked = noindegree.popleft()
            
            result.append(picked)
            
            for course in graph[picked]:
                indegree[course] -= 1
                
                if indegree[course] == 0:
                    noindegree.append(course)
        
        return result if len(result) == numCourses else []

No comments:

Post a Comment