题目

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.

1. 广度优先探索（BFS）
2. 深度优先探索（DFS）

广度优先探索（BFS）

代码

/**
* BFS Topological Sort
*/
public class SolutionV1 {
public int[] findOrder(int numCourses, int[][] prerequisites) {
// build degree table, and the prerequisites map
Map<Integer,List<Integer>> edges = new HashMap<>();
for (int i = 0; i < numCourses; i++) {
edges.put(i,new ArrayList<Integer>());
}
int[] degree = new int[numCourses];
for (int[] edge : prerequisites) {
degree[edge[0]]++;
}
// iteration from courses with 0 degree
int[] ret = new int[numCourses];
int cur = 0;
int count = 0;
do {
int size = zeroDegree.size();
for (int i = 0; i < size; i++) {
List<Integer> upperCourses = edges.remove(zeroDegree.poll());
for (int upper : upperCourses) {
degree[upper]--;
}
}
for (int i = 0; i < numCourses; i++) {
if (degree[i] == 0) {
zeroDegree.offer(i);
ret[cur++] = i;
count++;
degree[i] = -1;
}
}
} while (!zeroDegree.isEmpty());
return (count == numCourses)? ret : new int[0];
}
}


深度优先探索（DFS）

代码

/**
* DFS Topological Sort - post-order
*/
public class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
// Reduce the edges list into a Map. The map should not contains null entry
Map<Integer,List<Integer>> edges = new HashMap<>();
for (int i = 0; i < numCourses; i++) {
edges.put(i,new ArrayList<Integer>());
}
for (int[] edge : prerequisites) {
}
boolean[] finished = new boolean[numCourses];
List<Integer> postOrder = new ArrayList<>();
for (int i = 0; i < numCourses; i++) {
boolean findCircle = dfs(i,edges,new boolean[numCourses],finished,postOrder); // need a new log array each time
if (findCircle) { return new int[0]; }
}
int[] ret = new int[numCourses];
for (int i = 0; i < numCourses; i++) {
ret[i] = postOrder.get(i);
}
return ret;
}
/**
* return true if find circle, other wise return false
*/
public boolean dfs(int course, Map<Integer,List<Integer>> edges, boolean[] log, boolean[] finished, List<Integer> postOrder) {
// find circle? kill!
if (log[course] == true) { return true; }
// solved problem? kill!
if (finished[course]) { return false; }
// dfs backtracking recursion
List<Integer> pres = edges.remove(course);
log[course] = true;
for (int pre : pres) {
if (dfs(pre,edges,log,finished,postOrder)) { return true; } // find circle
}
log[course] = false;
finished[course] = true;
return false;
}
}


深度优先探索（DFS）的第二种方法

T(curr) = Max(T(pre)) + 1

代码

/**
* Topological Sort - DFS - Calculate Depth of Each Course
*/
public class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
// Reduce the edges list into a Map. The map should not contains null entry
Map<Integer,List<Integer>> edges = new HashMap<>();
for (int i = 0; i < numCourses; i++) {
edges.put(i,new ArrayList<Integer>());
}
for (int[] edge : prerequisites) {
}
int[] depth = new int[numCourses];
for (int i = 0; i < numCourses; i++) {
int d = dfs(i,edges,new boolean[numCourses],depth); // need a new log array each time
if (d == 0) { return new int[0]; } // find circle
}
// reduce depth into a Map
Map<Integer,List<Integer>> depthMap = new HashMap<>();
for (int i = 1; i <= numCourses; i++) {
depthMap.put(i,new ArrayList<Integer>());
}
for (int i = 0; i < numCourses; i++) {
}
int[] ret = new int[numCourses];
int cur = 0;
for (int i = 1; i <= numCourses; i++) {
List<Integer> level = depthMap.remove(i);
for (int course : level) {
ret[cur++] = course;
}
}
return ret;
}
/**
* return the depth of the course
* return 1 if this course has no prerequisites
* return 0 if find circle
*/
public int dfs(int course, Map<Integer,List<Integer>> edges, boolean[] log, int[] depth) {
// find circle? kill!
if (log[course] == true) { return 0; }
// solved problem? merge!
if (depth[course] > 0) { return depth[course]; }
// dfs backtracking recursion
List<Integer> pres = edges.remove(course);
int courseDepth = 1;
log[course] = true;
for (int pre : pres) {
int preDepth = dfs(pre,edges,log,depth);
if (preDepth == 0) {
return 0;
} else {
courseDepth = Math.max(courseDepth,preDepth+1);
}
}
log[course] = false;
depth[course] = courseDepth;
return courseDepth;
}
}