Problem description
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.
Example 1:
Input: 2, [[1,0]]
Output: [0,1]
Explanation: 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] .
Example 2:
Input: 4, [[1,0],[2,0],[3,1],[3,2]]
Output: [0,1,2,3] or [0,2,1,3]
Explanation: 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] .
Solution
This is a follow up for problem 207. For the same reason, we can solve it using either BFS or DFS. Below are my DFS and BFS solutions.
DFS
class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
color = ['White' for i in range(numCourses)]
edgemap = collections.defaultdict(list)
ans = []
for prerequisite in prerequisites:
x, y = prerequisite
edgemap[x].append(y)
def dfs(i:int, edgemap:dict)->bool:
color[i] = 'Grey'
for j in edgemap[i]:
if color[j] == 'White':
if dfs(j, edgemap) == False:
return False
elif color[j] == 'Black':
continue
else:
return False
color[i] = 'Black'
ans.append(i)
return True
for i in range(numCourses):
if color[i] == 'White':
if not dfs(i, edgemap):
return []
return ans
BFS
class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
indegrees = [0 for i in range(numCourses)]
edgemap = collections.defaultdict(set)
visited = [False for i in range(numCourses)]
ans = []
for prerequisite in prerequisites:
x, y = prerequisite
indegrees[y] += 1
edgemap[x].add(y)
print(indegrees)
while any(indegrees):
idx = -1
for i in range(numCourses):
if indegrees[i] == 0 and visited[i] == False:
visited[i] = True
idx = i
ans.append(idx)
break
else:
return []
for node in edgemap[idx]:
indegrees[node] -= 1
for i in range(numCourses):
if visited[i] == False:
ans.append(i)
return ans[::-1]