# LeetCode Course Schedule II

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.

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].

Solution:

Course Schedule一样，就是将拓扑的结果任意输出一个。然后发现一个bug，前面没注意到的，pre[i][0]是在pre[i][1]之后的意思……貌似方向搞反了

import java.util.*;

public class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
int n = numCourses;

int topo[] = new int[n];
int indegree[] = new int[n];
int mat[][] = new int[n][n];

for (int l = 0; l < prerequisites.length; l++) {
int j = prerequisites[l][0];
int i = prerequisites[l][1];
if (mat[i][j] == 1)
continue;
mat[i][j] = 1;
indegree[j]++;
}

int index;
for (int l = 0; l < n; l++) {
index = -1;
for (int i = 0; i < n; i++)
if (indegree[i] == 0) {
indegree[i] = -1;
index = i;
break;
}
if (index == -1)
return new int[0];
topo[l] = index;
for (int j = 0; j < n; j++)
if (mat[index][j] == 1)
indegree[j]--;
}

}
}

• 本文已收录于以下专栏：

## [LeetCode] Course Schedule II

Course Schedule II There are a total of n courses you have to take, labeled from 0 to n - 1. Som...

## LeetCode 210. Course Schedule II（课程安排）

• jmspan
• 2016年05月04日 17:09
• 380

## leetcode - 210. Course Schedule II

• Quiteen
• 2017年03月26日 13:17
• 185

## Leetcode 210. Course Schedule II

There are a total of n courses you have to take, labeled from 0 to n - 1.Some courses may have prere...

## LeetCode Algorithms 210. Course Schedule II

举报原因： 您举报文章：LeetCode Course Schedule II 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)