05 August 2008
给一个整数 n,表示从 1 到 n 有 n 门课程。您还得到一个数组关系,其中关系[i] = [prevCoursei, nextCoursei],表示课程 prevCoursei 和课程 nextCoursei 之间的先决关系:课程 prevCoursei 必须在课程 nextCoursei 之前学习。
在一个学期中,只要您已完成上学期所修课程的所有先决条件,您就可以修读任意数量的课程。
返回修读所有课程所需的最少学期数。如果无法参加所有课程,则返回-1。
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
Kahn's BFS topological ordering
*/
class Solution {
public int minimumSemesters(int n, int[][] relations) {
// indegree array, 0 indeg means 0 prereq. This is in contrast to Post Order DFS toposort.
int[] preReq = new int[n + 1]; // n+1 bcz courses are numbered from 1
for (int[] rel : relations) {
preReq[rel[1]] += 1; // rel[1] is the course that has rel[0] as its preReq
}
Queue<Integer> zeroPreQ = new LinkedList<>();
for (int i = 1; i <= n; i++) { // 1 index array, bcz courses are numbered from 1
if (preReq[i] == 0)
zeroPreQ.offer(i);
}
if (zeroPreQ.isEmpty())
return -1;
boolean[] completed = new boolean[n + 1];
HashMap<Integer, List<Integer>> nextCourseMap = nextCourseMap(relations);
int noOfSem = 0;
while (!zeroPreQ.isEmpty()) {
noOfSem++;
int curSemCourses = zeroPreQ.size();
while (curSemCourses > 0) {
int course = zeroPreQ.poll();
completed[course] = true;
curSemCourses--;
List<Integer> nextCourses = nextCourseMap.get(course);
if (nextCourses != null) {
for (int nextCourse : nextCourses) {
if (!completed[nextCourse]) {
preReq[nextCourse] -= 1;
if (preReq[nextCourse] == 0)
zeroPreQ.add(nextCourse);
}
}
}
}
}
for (int i = 1; i <= n; i++) {
if (!completed[i])
return -1;
}
return noOfSem;
}
//Instead of prereq as list (like in dfs topo), we add, the next course as list here
HashMap<Integer, List<Integer>> nextCourseMap(int[][] relations) {
HashMap<Integer, List<Integer>> nextCourseMap = new HashMap<Integer, List<Integer>>();
for (int[] rel : relations) {
List<Integer> nextCourses = nextCourseMap.getOrDefault(rel[0], new ArrayList());
nextCourses.add(rel[1]);
nextCourseMap.put(rel[0], nextCourses);
}
return nextCourseMap;
}
}