-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path207.py
28 lines (26 loc) · 936 Bytes
/
207.py
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
# https://neetcode.io/problems/course-schedule
# https://leetcode.com/problems/course-schedule/description/
from collections import defaultdict
from typing import List
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
graph = defaultdict(list)
for course, prereq in prerequisites:
graph[course].append(prereq)
visited = set()
def containsCycle(course):
if course not in graph:
return False
if course in visited:
return True
visited.add(course)
for prereq in graph[course]:
if containsCycle(prereq):
return True
del graph[course]
visited.remove(course)
return False
for course in list(graph):
if containsCycle(course):
return False
return True