官方题解主要思想是使用dfs进行拓扑排序。
课程表
class Solution:def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:edges = collections.defaultdict(list) visited = [0] * numCourses # 将列表初始化为numCourses个0# result = []valid = Truefor info in prerequisites:edges[info[1]].append(info[0]) # info[1]是哪些课程的依赖(先决条件) def dfs(u: int):nonlocal validvisited[u] = 1for v in edges[u]:if visited[v] == 0:dfs(v)if not valid:returnelif visited[v] == 1:valid = Falsereturnvisited[u] = 2# result.append(u)for i in range(numCourses):if valid and not visited[i]:dfs(i)return valid
课程表二
class Solution:def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:edges = collections.defaultdict(list)visited = [0]*numCoursesresult = []valid =Truefor info in prerequisites:edges[info[1]].append(info[0])def dfs(u):nonlocal validvisited[u]=1for v in edges[u]:if visited[v]==0:dfs(v)elif visited[v]==1:valid=Falsereturn visited[u]=2result.append(u)for i in range(numCourses):if valid and not visited[i]:dfs(i)if valid==True:result.reverse()return resultelse:return []