-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path210. Course Schedule II(BFS).js
59 lines (52 loc) · 1.47 KB
/
210. Course Schedule II(BFS).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
55
56
57
58
59
'use strict';
/**
* @param {number} numCourses
* @param {number[][]} prerequisites
* @return {number[]}
*/
var findOrder = function(numCourses, prerequisites) {
let result = new Array();
if (numCourses === 0) {
return [0];
}
if (prerequisites.length === 0 || prerequisites[0].length === 0) {
for (let i = 0; i < numCourses; i++) {
result.unshift(i);
}
return result;
}
if (prerequisites === null) {
throw new Error('illegal argument exception!');
}
//when node without indegree, push node into the queue, when queue is empty, return queue.length === numCourses
let queue = new Array();
let inDegree = new Array(numCourses).fill(0);
let length = prerequisites.length;
for (let i = 0; i < length; i++) {
inDegree[prerequisites[i][0]]++;
}
for (let i = 0; i < numCourses; i++) {
if (inDegree[i] === 0) {
queue.push(i);
}
}
let noPreNum = 0;
while(!(queue.length === 0)) {
let target = queue.shift();
result.push(target);
noPreNum++;
for (let i = 0; i < length; i++) {
if (prerequisites[i][1] === target) {
inDegree[prerequisites[i][0]]--;
if (inDegree[prerequisites[i][0]] === 0) {
queue.push(prerequisites[i][0]);
}
}
}
}
if (noPreNum !== numCourses) {
return [];
} else {
return result;
}
};