|
| 1 | +''' |
| 2 | +There are a total of n courses you have to take, labeled from 0 to n-1. |
| 3 | +
|
| 4 | +Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] |
| 5 | +
|
| 6 | +Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses? |
| 7 | +
|
| 8 | +Example 1: |
| 9 | +
|
| 10 | +Input: 2, [[1,0]] |
| 11 | +Output: true |
| 12 | +Explanation: There are a total of 2 courses to take. |
| 13 | + To take course 1 you should have finished course 0. So it is possible. |
| 14 | +Example 2: |
| 15 | +
|
| 16 | +Input: 2, [[1,0],[0,1]] |
| 17 | +Output: false |
| 18 | +Explanation: There are a total of 2 courses to take. |
| 19 | + To take course 1 you should have finished course 0, and to take course 0 you should |
| 20 | + also have finished course 1. So it is impossible. |
| 21 | +Note: |
| 22 | +
|
| 23 | + 1. The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented. |
| 24 | + 2. You may assume that there are no duplicate edges in the input prerequisites. |
| 25 | +''' |
| 26 | + |
| 27 | + |
| 28 | +class Solution: |
| 29 | + def canFinish(self, numCourses: int, prerequisites: [[]]) -> bool: |
| 30 | + graph = {n: [] for n in range(numCourses)} |
| 31 | + for x, y in prerequisites: |
| 32 | + graph[x].append(y) |
| 33 | + |
| 34 | + for target in range(numCourses): |
| 35 | + stack = graph[target] |
| 36 | + visited = set() |
| 37 | + while stack: |
| 38 | + course = stack.pop() |
| 39 | + visited.add(course) |
| 40 | + if course == target: |
| 41 | + return False |
| 42 | + for i in graph[course]: |
| 43 | + if i not in visited: |
| 44 | + stack.append(i) |
| 45 | + return True |
| 46 | + |
| 47 | + |
| 48 | +if __name__ == "__main__": |
| 49 | + assert True == Solution().canFinish(2, [[1, 0]]) |
| 50 | + assert False == Solution().canFinish(2, [[1, 0], [0, 1]]) |
0 commit comments