본문 바로가기

0/leetcode

207. Course Schedule

반응형

leetcode.com/problems/course-schedule/

 

Course Schedule - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

import collections

class Solution:
    def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
        
        indegrees = [0]*numCourses
        graph = defaultdict(list)
        
        for u, v in prerequisites :
            indegrees[v] += 1
            graph[u].append(v)

        q = deque([])
        
        for i in range(len(indegrees)) :
            if indegrees[i] == 0 :
                q.append(i)
                
        finished = 0
        
        while q :
            
            curr = q.popleft()
            finished += 1
            
            for i in graph[curr] :
                indegrees[i] -= 1
                if indegrees[i] == 0 :
                    q.append(i)
                    
        return finished == numCourses
    

 

정리 :

순서가 있는 문제는 위상정렬 사용.

recursive보다는 iterative로 접근.

반응형

'0 > leetcode' 카테고리의 다른 글

784. Letter Case Permutation  (0) 2020.09.10
55. Jump Game  (0) 2020.09.09
41. First Missing Positive  (0) 2020.09.08
988. Smallest String Starting From Leaf  (0) 2020.09.08
16. 3Sum Closest  (0) 2020.09.08