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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
|
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: indegrees = [0 for _ in range(numCourses)] adjacency = [[] for _ in range(numCourses)] queue = deque() for cur, pre in prerequisites: indegrees[cur] += 1 adjacency[pre].append(cur) for i in range(len(indegrees)): if not indegrees[i]: queue.append(i) while queue: pre = queue.popleft() numCourses -= 1 for cur in adjacency[pre]: indegrees[cur] -= 1 if not indegrees[cur]: queue.append(cur) return not numCourses
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: def dfs(i, adjacency, flags): if flags[i] == -1: return True if flags[i] == 1: return False flags[i] = 1 for j in adjacency[i]: if not dfs(j, adjacency, flags): return False flags[i] = -1 return True
adjacency = [[] for _ in range(numCourses)] flags = [0 for _ in range(numCourses)] for cur, pre in prerequisites: adjacency[pre].append(cur) for i in range(numCourses): if not dfs(i, adjacency, flags): return False return True
|