-
Notifications
You must be signed in to change notification settings - Fork 0
/
207.course-schedule.js
44 lines (43 loc) · 968 Bytes
/
207.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
/*
* @lc app=leetcode id=207 lang=javascript
*
* [207] Course Schedule
*/
// @lc code=start
/**
* @param {number} numCourses
* @param {number[][]} prerequisites
* @return {boolean}
*/
const canFinish = function (numCourses, prerequisites) {
const preCounts = {};
const nextCourse = {};
for (const [course, pre] of prerequisites) {
if (!nextCourse[pre]) {
nextCourse[pre] = [];
}
nextCourse[pre].push(course);
preCounts[course] = preCounts[course] + 1 || 1;
}
const q = [];
for (let courseNum = 0; courseNum < numCourses; courseNum++) {
if (!preCounts[courseNum]) {
q.push(courseNum);
}
}
const taken = q.slice();
while (q.length) {
const c = q.shift();
if (nextCourse[c]) {
for (const n of nextCourse[c]) {
preCounts[n]--;
if (!preCounts[n]) {
taken.push(n);
q.push(n);
}
}
}
}
return taken.length === numCourses;
};
// @lc code=end