-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path207_Course_Schedule.py
More file actions
35 lines (26 loc) · 923 Bytes
/
Copy path207_Course_Schedule.py
File metadata and controls
35 lines (26 loc) · 923 Bytes
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
class Solution:
def __init__(self):
self.visited = set()
self.adj_list = {}
def canFinish(self, numCourses: int, prerequisites: list[list[int]]) -> bool:
# Initialize adjacency list
for i in range(numCourses):
self.adj_list[i] = []
# Build graph
for course, prereq in prerequisites:
self.adj_list[course].append(prereq)
# Check each course
for course in range(numCourses):
if not self.dfs(course):
return False
return True
def dfs(self, node: int) -> bool:
if node in self.visited:
return False
self.visited.add(node)
for neighbor in self.adj_list[node]:
if not self.dfs(neighbor):
return False
self.visited.remove(node)
self.adj_list[node] = [] # Memoize as already processed
return True