Created
January 6, 2017 22:33
-
-
Save liondancer/fa0c95aeb4405ed3089b065b35c6b454 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def canFinish(numCourses, prerequisites): | |
""" | |
:type numCourses: int | |
:type prerequisites: List[List[int]] | |
:rtype: bool | |
""" | |
if prerequisites: | |
# create graph | |
courses = {} | |
finished_courses = [] | |
for i in range(numCourses): | |
courses[i] = set() | |
# put prereqs | |
for prereq in prerequisites: | |
courses[prereq[0]].add(prereq[1]) | |
# find classes without prereqs and add to queue to complete first | |
queue = [] | |
for course in courses: | |
# pass if empty set | |
if not courses[course]: | |
queue.append(course) | |
while queue: | |
course = queue.pop() | |
for c, r in courses.items(): | |
if course in r: | |
r.remove(course) | |
if not r: | |
queue.append(c) | |
finished_courses.append(course) | |
return len(finished_courses) == numCourses | |
return True | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment