8/27/2020

[LeetCode] 207. Course Schedule

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

Topological Sort


class Solution:
    def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
        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)
            
        totalPicked = 0
        
        while noindegree:
            picked = noindegree.popleft()
            
            totalPicked += 1
            
            for course in graph[picked]:
                indegree[course] -= 1
                
                if indegree[course] == 0:
                    noindegree.append(course)
        
        return totalPicked == numCourses

No comments:

Post a Comment