-
Notifications
You must be signed in to change notification settings - Fork 310
/
Copy pathcourse-schedule.js
47 lines (39 loc) · 928 Bytes
/
course-schedule.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
// Source : https://leetcode.com/problems/course-schedule/
// Author : Han Zichi
// Date : 2016-08-28
/**
* @param {number} numCourses
* @param {number[][]} prerequisites
* @return {boolean}
*/
var canFinish = function(numCourses, prerequisites) {
var map = []; // 邻接表
var indegree = []; // 入度
for (var i = 0; i < numCourses; i++)
map[i] = [], indegree[i] = 0;
prerequisites.forEach(function(item) {
var from = item[1];
var to = item[0];
map[from].push(to);
indegree[to]++;
});
var q = [];
var finishNum = 0;
for (var i = 0; i < numCourses; i++) {
// 入度为 0,没有依赖
if (!indegree[i]) {
q.push(i);
finishNum++;
}
}
while (q.length) {
var from = q.shift();
map[from].forEach(function(to) {
if (--indegree[to] === 0) {
q.push(to);
finishNum++;
}
});
}
return finishNum === numCourses;
};