-
Notifications
You must be signed in to change notification settings - Fork 198
/
Copy pathleetcode 207 - course schedule.py
46 lines (34 loc) · 1.29 KB
/
leetcode 207 - 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
35
36
37
38
39
40
41
42
43
44
45
46
# course schedule | leetcode 207 | https://leetcode.com/problems/course-schedule/
# method: depth first search
class Solution:
def canFinish(self, numCourses: int, prerequisites) -> bool:
# init prequisite map
preqMap = {}
for i in range(numCourses):
preqMap[i] = []
# add mentioned prerequisites
for crs, pre in prerequisites:
preqMap[crs].append(pre)
# init visit set
visitSet = set()
# dfs
def checkPreq(crs):
# if course is already visited
if crs in visitSet:
return False
# if no prequisites left
if preqMap[crs] == []:
return True
# visiting this course
visitSet.add(crs)
# checking each prerequisite
for pre in preqMap[crs]:
if not checkPreq(pre): return False
# all prerequisites are doable
visitSet.remove(crs)
preqMap[crs] = []
return True
# check prerequisites for each course
for crs in range(numCourses):
if not checkPreq(crs): return False
return True