-
Notifications
You must be signed in to change notification settings - Fork 2
/
210.course-schedule-ii.java
64 lines (52 loc) · 1.53 KB
/
210.course-schedule-ii.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
* @lc app=leetcode id=210 lang=java
*
* [210] Course Schedule II
*/
// @lc code=start
class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
//Topological sorting
if (numCourses < 0) {
return new int[]{};
}
Queue<Integer> queue = new LinkedList<>();
int[] inDegree = new int[numCourses];
int[] result = new int[numCourses];
//indegree counting
for (int i = 0; i < prerequisites.length; i++) {
inDegree[prerequisites[i][0]]++;
}
//add the course with 0 indegree
for (int i = 0; i < inDegree.length; i++) {
if (inDegree[i] == 0) {
queue.add(i);
}
}
int level = 0;
while (!queue.isEmpty()) {
int currIndex = queue.poll();
result[level] = currIndex;
for (int i = 0; i < prerequisites.length; i++) {
if (currIndex == prerequisites[i][1]) {
inDegree[prerequisites[i][0]]--;
if (inDegree[prerequisites[i][0]] == 0) {
queue.add(prerequisites[i][0]);
}
}
}
level++;
}
//check
boolean flag = true;
for (int i = 0; i < inDegree.length; i++) {
if (inDegree[i] != 0)
flag = false;
}
if (flag) {
return result;
}
return new int[]{};
}
}
// @lc code=end