-
Notifications
You must be signed in to change notification settings - Fork 0
/
course_schedule.py
34 lines (27 loc) · 941 Bytes
/
course_schedule.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import collections
from typing import List
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
res = []
indegrees = {i: 0 for i in range(numCourses)}
graph = {i: [] for i in range(numCourses)}
for pre, crs in prerequisites:
graph[pre].append(crs)
indegrees[crs] += 1
sources = collections.deque()
for key in indegrees:
if indegrees[key] == 0:
sources.append(key)
while sources:
vertex = sources.popleft()
res.append(vertex)
for child in graph[vertex]:
indegrees[child] -= 1
if indegrees[child] == 0:
sources.append(child)
if len(res) != numCourses:
return False
return True
if __name__ == "__main__":
s = Solution()
print(s.canFinish(2, [[1, 0], [0, 1]]))