|
| 1 | +# 207. Course Schedule |
| 2 | + |
| 3 | +## DFS Recursive Solution |
| 4 | +- Runtime: O(N) |
| 5 | +- Space: O(N) |
| 6 | +- N = Number of courses |
| 7 | + |
| 8 | +When the problem has relationships, such as a course needing more than one prerequisite, you can think of a graph. |
| 9 | +In this case, its a directed graph. |
| 10 | +The core of the problem is to find a cycle in the graph, as example 2 of the problem shows that. |
| 11 | + |
| 12 | +We will need to create a graph, as it is not provided to us, it can be an adjacent list or a matrix, doesn't matter. |
| 13 | +For any dfs, you will need a global visited and a local visited. |
| 14 | +The global visited will tell us if we need to dfs starting at this node, this is to reduce run-time, else it will be O(N^N). |
| 15 | +The local visited is for when we are traversing the graph via. dfs and looking for cycles. |
| 16 | +I decided to use a dictionary to simplify the code, -1 will be used during the dfs, then after the dfs, changed into a 1, showing that its already visited and has no cycles. |
| 17 | + |
| 18 | +``` |
| 19 | +from collections import defaultdict |
| 20 | +
|
| 21 | +class Solution: |
| 22 | + def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: |
| 23 | + adj_list = self.create_adj_list(prerequisites) |
| 24 | + visited = defaultdict(int) |
| 25 | + for node in adj_list: |
| 26 | + if not self.dfs(node, adj_list, visited): |
| 27 | + return False |
| 28 | + return True |
| 29 | + |
| 30 | + def dfs(self, node, adj_list, visited): |
| 31 | + if visited[node] == -1: # currently visiting, cycle |
| 32 | + return False |
| 33 | + if visited[node] == 1: # already visited, no cycle |
| 34 | + return True |
| 35 | + visited[node] = -1 |
| 36 | + for neighbor in adj_list[node]: |
| 37 | + if not self.dfs(neighbor, adj_list, visited): |
| 38 | + return False |
| 39 | + visited[node] = 1 |
| 40 | + return True |
| 41 | + |
| 42 | + def create_adj_list(self, prereqs): |
| 43 | + adj_list = defaultdict(list) |
| 44 | + for course, prereq in prereqs: |
| 45 | + adj_list[course].append(prereq) |
| 46 | + adj_list[prereq] |
| 47 | + return adj_list |
| 48 | +``` |
0 commit comments