-
Notifications
You must be signed in to change notification settings - Fork 0
/
course-schedule
34 lines (31 loc) · 1.11 KB
/
course-schedule
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
/** https://leetcode.com/problems/course-schedule/
* @param {number} numCourses
* @param {number[][]} prerequisites
* @return {boolean}
*/
var canFinish = function(numCourses, prerequisites) {
let course_dependencyMap = {};
let actual = numCourses;
let solved = false, filtered, curr_key;
while (--numCourses >= 0) {
course_dependencyMap[numCourses] = [];
}
prerequisites.forEach(prerequisity=>course_dependencyMap[prerequisity[0]].push(prerequisity[1]));
while (true) {
filtered = [];
Object.entries(course_dependencyMap).forEach(([key,values])=>{
if(values.length === 0){
actual--;
delete course_dependencyMap[key];
filtered.push(Number(key));
}});
if (filtered.length === 0) {
break;
} else if (filtered.length === actual || !actual) {
solved = true;
break;
};
Object.entries(course_dependencyMap).forEach(([key,values])=>course_dependencyMap[key] = course_dependencyMap[key].filter(val=>filtered.indexOf(val) === -1));
}
;return solved;
};