classSolution: defcanFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: indegrees = [0for _ inrange(numCourses)] adjacency = [[] for _ inrange(numCourses)] queue = deque() # Get the indegree and adjacency of every course. for cur, pre in prerequisites: indegrees[cur] += 1 adjacency[pre].append(cur) # Get all the courses with the indegree of 0. for i inrange(len(indegrees)): ifnot indegrees[i]: queue.append(i) # BFS TopSort. while queue: pre = queue.popleft() numCourses -= 1 for cur in adjacency[pre]: indegrees[cur] -= 1 ifnot indegrees[cur]: queue.append(cur) returnnot numCourses
解法2:使用DFS
原理是通过 DFS 判断图中是否有环。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution: defcanFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: defdfs(i, adjacency, flags): if flags[i] == -1: returnTrue if flags[i] == 1: returnFalse flags[i] = 1 for j in adjacency[i]: ifnot dfs(j, adjacency, flags): returnFalse flags[i] = -1 returnTrue
adjacency = [[] for _ inrange(numCourses)] flags = [0for _ inrange(numCourses)] for cur, pre in prerequisites: adjacency[pre].append(cur) for i inrange(numCourses): ifnot dfs(i, adjacency, flags): returnFalse returnTrue