- Course Schedule II
There are a total of n courses you have to take, labeled from 0 to n - 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, return the ordering of courses you should take to finish all courses.
There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.
For example:
2, [[1,0]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]
4, [[1,0],[2,0],[3,1],[3,2]]
There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is[0,2,1,3].
Note:
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.
click to show more hints.
Hints:
This problem is equivalent to finding the topological order in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses.
Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort.
Topological sort could also be done via BFS.
my thoughts:
1. find all prerequisites for each course that has a prerequisite (key in prerequisites); for all course that has no prerequisite, set their level at 1; for courses that have prerequisites, dfs the level (what is the max layers to get to it), sort the courses by level.
my solution:
**********128ms
class Solution:
def findOrder(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: List[int]
"""
d = {}
self.dc = {}
for p in prerequisites:
d[p[0]] = d.get(p[0], []) + [p[1]]
for i in range(numCourses):
if i not in d:
self.dc[i] = 1
if not self.dc:
return []
def dfs(k, d, h, nC):
if h > nC:
return -1
temp = -1
for c in d[k]:
if c in self.dc:
temp = max(temp, self.dc[c])
else:
temp = dfs(c, d, h+1, nC)
if temp == -1:
return -1
return temp + h
for k in d:
if k in self.dc:
continue
height = dfs(k, d, 1, numCourses)
if height == -1:
return []
self.dc[k] = height
res = sorted(self.dc.items(), key = lambda x: x[1])
return [x[0] for x in res]
my comments:
from other ppl's solution:
1. # BFS
def findOrder1(self, numCourses, prerequisites):
dic = {i: set() for i in xrange(numCourses)}
neigh = collections.defaultdict(set)
for i, j in prerequisites:
dic[i].add(j)
neigh[j].add(i)
# queue stores the courses which have no prerequisites
queue = collections.deque([i for i in dic if not dic[i]])
count, res = 0, []
while queue:
node = queue.popleft()
res.append(node)
count += 1
for i in neigh[node]:
dic[i].remove(node)
if not dic[i]:
queue.append(i)
return res if count == numCourses else []
# DFS
def findOrder(self, numCourses, prerequisites):
dic = collections.defaultdict(set)
neigh = collections.defaultdict(set)
for i, j in prerequisites:
dic[i].add(j)
neigh[j].add(i)
stack = [i for i in xrange(numCourses) if not dic[i]]
res = []
while stack:
node = stack.pop()
res.append(node)
for i in neigh[node]:
dic[i].remove(node)
if not dic[i]:
stack.append(i)
dic.pop(node)
return res if not dic else []
2. Topological sort, 78ms:
class Solution:
def dfsTopoSort(self, visit, edge, time, ind):
visit[ind] = 0
if ind in edge:
for i in edge[ind]:
if visit[i] == -1:
self.dfsTopoSort(visit, edge, time, i)
visit[ind] = time[0]
time[0] += 1
def findOrder(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: bool
"""
edge = {}
for item in prerequisites:
(l, r) = item
if l not in edge:
edge[l] = [r]
else:
edge[l].append(r)
visit = [-1] * numCourses
time = [1]
for i in range(numCourses):
if visit[i] == -1:
self.dfsTopoSort(visit, edge, time, i)
#print(time)
#print(list(range(numCourses)))
#print(visit)
for item in prerequisites:
(l, r) = item
if visit[l] < visit[r]:
return []
ans = sorted(list(range(numCourses)), key = lambda x : visit[x])
return ans