Skip to content

Commit 5ccca87

Browse files
author
Joseph Luce
authored
Update 207_course_schedule.md
1 parent 092067b commit 5ccca87

File tree

1 file changed

+24
-25
lines changed

1 file changed

+24
-25
lines changed

leetcode/medium/207_course_schedule.md

Lines changed: 24 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -11,39 +11,38 @@ The core of the problem is to find a cycle in the graph, as example 2 of the pro
1111

1212
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.
1313
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).
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^2).
1515
The local visited is for when we are traversing the graph via. dfs and looking for cycles.
1616

17-
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. You can always use two separate visited sets but I find the code gets clunky.
18-
1917
```
2018
from collections import defaultdict
2119
2220
class Solution:
2321
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
24-
adj_list = self.create_adj_list(prerequisites)
25-
visited = defaultdict(int)
26-
for node in adj_list:
27-
if not self.dfs(node, adj_list, visited):
28-
return False
29-
return True
30-
31-
def dfs(self, node, adj_list, visited):
32-
if visited[node] == -1: # currently visiting, cycle
33-
return False
34-
if visited[node] == 1: # already visited, no cycle
22+
def create_graph():
23+
graph = defaultdict(list)
24+
for course, prereq in prerequisites:
25+
graph[course].append(prereq)
26+
graph[prereq]
27+
return graph
28+
29+
def dfs(course, graph, visited, global_visited):
30+
if course in visited:
31+
return False # found cycle
32+
if course in global_visited:
33+
return True
34+
visited.add(course)
35+
global_visited.add(course)
36+
for prereq in graph[course]:
37+
if not dfs(prereq, graph, visited, global_visited):
38+
return False
39+
visited.remove(course)
3540
return True
36-
visited[node] = -1
37-
for neighbor in adj_list[node]:
38-
if not self.dfs(neighbor, adj_list, visited):
41+
42+
graph = create_graph() # key: course, val: list of prereqs
43+
global_visited = set()
44+
for course in graph:
45+
if not dfs(course, graph, set(), global_visited): # cycle
3946
return False
40-
visited[node] = 1
4147
return True
42-
43-
def create_adj_list(self, prereqs):
44-
adj_list = defaultdict(list)
45-
for course, prereq in prereqs:
46-
adj_list[course].append(prereq)
47-
adj_list[prereq]
48-
return adj_list
4948
```

0 commit comments

Comments
 (0)