There are a total of numCourses courses you have to take, labeled from
0tonumCourses - 1. You are given an array prerequisites whereprerequisites[i] = [ai, bi]indicates that you must take coursebifirst if you want to take courseai.For example, the pair
[0, 1], indicates that to take course0you have to first take course1.Return
trueif you can finish all courses. Otherwise, returnfalse.Constraints:
1 <= numCourses <= 20000 <= prerequisites.length <= 5000prerequisites[i].length == 20 <= ai, bi < numCourses- All the pairs
prerequisites[i]are unique.
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
def dfs(root: int) -> bool:
if root not in graph: return True
if state[root] == 1: return False
if state[root] == 2: return True
state[root] = 1
for course in graph[root]:
if not dfs(course):
return False
state[root] = 2
return True
state = {i: 0 for i in range(numCourses)}
graph = {}
for edge in prerequisites:
course, prereq = edge[0], edge[1]
if prereq not in graph:
graph[prereq] = []
if course not in graph:
graph[course] = []
graph[prereq].append(course)
for i in range(numCourses):
if not dfs(i):
return False
return True