-
Notifications
You must be signed in to change notification settings - Fork 481
/
1136.js
36 lines (34 loc) · 797 Bytes
/
1136.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
var minimumSemesters = function(N, relations) {
var g = Array(N);
var degrees = Array(N);
degrees.fill(0);
for (let [i, j] of relations) {
i--;
g[i] = g[i] || [];
g[i].push(--j);
degrees[j]++;
}
var num = 0, res = 0;
var q = Array();
for (var i = 0; i < N; ++i) {
if (degrees[i] == 0) {
num++;
q.push(i);
}
}
while (q.length > 0) {
var n = q.length;
while (n--) {
var v = q.shift();
for (let w of g[v] || []) {
degrees[w]--;
if (degrees[w] == 0) {
q.push(w);
num++;
}
}
}
res++;
}
return num == N ? res : -1;
};