-
Notifications
You must be signed in to change notification settings - Fork 0
/
course-schedule-ii.js
54 lines (40 loc) · 1.13 KB
/
course-schedule-ii.js
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
/**
* @param {number} numCourses
* @param {number[][]} prerequisites
* @return {number[]}
*/
var findOrder = function(numCourses, prerequisites) {
// Initialize result array
const result = new Array(numCourses).fill(0)
const inDegree = new Array(numCourses).fill(0);
for(const pre of prerequisites) {
inDegree[pre[0]]++
}
const zeroDegree = [];
for(let i = 0; i < numCourses; i++) {
if(inDegree[i]===0) {
zeroDegree.push(i);
}
}
// Topological sort not possible
if(zeroDegree.length === 0) return []
let i = 0
while(zeroDegree.length) {
const course = zeroDegree.pop()
// Add course to the result array
result[i++] = course
for(const pre of prerequisites) {
if(course === pre[1]) {
inDegree[pre[0]]--
if(inDegree[pre[0]]===0) {
zeroDegree.push(pre[0])
}
}
}
}
// Topological sort not possible
for(const num of inDegree) {
if(num!== 0) return []
}
return result;
};