-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathcourseschedule.py
45 lines (30 loc) · 1.37 KB
/
courseschedule.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
35
36
37
38
39
40
41
42
43
44
45
'''
There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.
For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.
Return true if you can finish all courses. Otherwise, return false.
'''
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
adjDict = {}
for i in range(numCourses):
adjDict[i] = []
for course, prereq in prerequisites:
adjDict[course].append(prereq)
visitSet = set()
def dfs(course):
if course in visitSet:
#there is a loop
return False
if adjDict[course] == []:
return True
visitSet.add(course)
for prereq in adjDict[course]:
if not dfs(prereq):
return False
visitSet.remove(course)
adjDict[course] = []
return True
for course in range(numCourses):
if not dfs(course):
return False
return True