207. Course Schedule (Python)
Related Topic
Breadth-First-Search. Topological-Sort. Graph.
Description
There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?
Sample I/O
Example 1
Input: numCourses = 2, prerequisites = [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
Example 2
Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
Output: false
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you should
also have finished course 1. So it is impossible.
Constrains
- The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
- You may assume that there are no duplicate edges in the input prerequisites.
- 1 <= numCourses <= 10^5
Methodology
This is a graph question. Any graph question to get directed acyclic graph (DAG) should think about using the topologic sort. This question is great practices. We return false if there is cycle in this graph otherwise return true.
First we build up two distionary, one is for all courses with their prerequesties and the other is the all prerequesties with their courses. Now we iterate all couses number and find the couses that has no prerequesties and append it to stack and we keep counting such course. For the couses which does not have prerequesties, they may be other couses’ prequesties now we need to find these couses. From these couses’ prerequesties we remove the the couse that we jsut find that does not have prerequesties. After remove if the couse has no prequesties, then we append this course to the stack. We keep iterating the stack until the stack is empty now we need to compare the count and given numCourses if they are equal we return true.
BFS:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
courses = collections.defaultdict(set)
pres = collections.defaultdict(set)
for course, pre in prerequisites:
courses[course].add(pre)
pres[pre].add(course)
no_pre_courses = [n for n in range(numCourses) if not courses[n]]
count = 0
while no_pre_courses:
no_pre = no_pre_courses.pop()
count+=1
for course in pres[no_pre]:
courses[course].remove(no_pre)
if not courses[course]:
no_pre_courses.append(course)
return count == numCourses
BigO
Time Complexity: O(E+V) where V is the number of courses, and E is the number of dependencies.