给出一些课程的先修课程,求出修完所有课程的顺序。
拓扑排序的裸题:
public int[] findOrder(int numCourses, int[][] prerequisites) {
int[][] matrix = new int[numCourses][numCourses]; // i -> j
int[] indegree = new int[numCourses];
for (int i = 0; i < prerequisites.length; i++) {
int ready = prerequisites[i][0];
int pre = prerequisites[i][1];
if (matrix[pre][ready] == 0) //多重边
indegree[ready]++;
matrix[pre][ready] = 1;
}
int count = 0;
int[] res = new int[numCourses];
Queue<Integer> queue = new LinkedList();
//所有入度为0的点
for (int i = 0; i < indegree.length; i++) {
if (indegree[i] == 0) queue.offer(i);
}
while (!queue.isEmpty()) {
int course = queue.poll();
res[count] = course;
count++; //已经学完的课程
for (int i = 0; i < numCourses; i++) {
if (matrix[course][i] != 0) {
//编号为i的课程的先修课程都已经学完
if (--indegree[i] == 0)
queue.offer(i);
}
}
}
if (count == numCourses) {
return res;
} else {
return new int[0];
}
}