- class Solution:
- def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
- rd=[0]*numCourses #入度
- dic=collections.defaultdict(list)
- res=0
- for i in prerequisites:
- rd[i[0]]+=1
- dic[i[1]].append(i[0]) #更新入度和后继课程
- q=collections.deque([i for i in range(numCourses) if rd[i]==0]) #初始化入度为0可学课程
- while q:
- a=q.popleft()
- res+=1
- for i in dic[a]:
- rd[i]-=1 #弹出入度为0的课程,后继课程入度减一
- if rd[0]==0:
- q.append(i) #入度为0弹出
- return res==numCourses