-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path207.course-schedule.js
54 lines (50 loc) · 1.12 KB
/
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
45
46
47
48
49
50
51
52
53
/*
* @lc app=leetcode id=207 lang=javascript
*
* [207] Course Schedule
*/
// @lc code=start
/**
* @param {number} numCourses
* @param {number[][]} prerequisites
* @return {boolean}
*/
const make_graph = (prerequisites) => {
const graph = {}
for (let cources of prerequisites) {
const preCource = cources[1]
const cource = cources[0]
if (!graph[preCource]) graph[preCource] = []
graph[preCource].push(cource)
}
return graph
}
const calIndegree = (graph) => {
const indegree = {}
Object.values(graph).forEach(cources => {
cources.forEach(c => {
if (indegree[c]) indegree[c] += 1
else indegree[c] = 1
})
})
return indegree
}
var canFinish = function (numCourses, prerequisites) {
const graph = make_graph(prerequisites)
const indegreeNode = calIndegree(graph)
for (let i = 0; i < numCourses; i++) {
let j = 0;
for (; j < numCourses; j++) {
if (!indegreeNode[j]) break
}
if (j === numCourses) return false
indegreeNode[j] = -1
if (graph[j]) {
for (let n of graph[j]) {
indegreeNode[n]--
}
}
}
return true
};
// @lc code=end