-
Notifications
You must be signed in to change notification settings - Fork 1
/
CourseScheduleII.java
46 lines (45 loc) · 1.33 KB
/
CourseScheduleII.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
/**
* 210. Course Schedule II.
* 拓扑排序(利用BFS)
* @author LBW
*/
public class CourseScheduleII {
public int[] findOrder(int numCourses, int[][] prerequisites) {
List<List<Integer>> courseGraph = new ArrayList<>();
for (int i = 0; i < numCourses; i++) {
courseGraph.add(new ArrayList<>());
}
int[] courseInDegree = new int[numCourses];
for (int[] pre: prerequisites) {
courseGraph.get(pre[1]).add(pre[0]);
courseInDegree[pre[0]] += 1;
}
// topo sort
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < numCourses; i++) {
if (courseInDegree[i] == 0) {
queue.offer(i);
}
}
int[] ans = new int[numCourses];
int idx = 0;
while (!queue.isEmpty()) {
int course = queue.poll();
ans[idx++] = course;
for (int next: courseGraph.get(course)) {
courseInDegree[next] -= 1;
if (courseInDegree[next] == 0) {
queue.offer(next);
}
}
}
if (idx == numCourses) {
return ans;
}
return new int[]{};
}
}