Skip to content

Commit dd72980

Browse files
authored
Update 207-course-schedule.js
1 parent 88674e2 commit dd72980

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

207-course-schedule.js

+43
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,46 @@
1+
/**
2+
* @param {number} numCourses
3+
* @param {number[][]} prerequisites
4+
* @return {boolean}
5+
*/
6+
const canFinish = function (numCourses, prerequisites) {
7+
const set = new Set()
8+
const indegree = Array(numCourses).fill(0)
9+
const graph = {}
10+
11+
for (const [s, e] of prerequisites) {
12+
indegree[e]++
13+
if (graph[s] == null) graph[s] = []
14+
graph[s].push(e)
15+
}
16+
17+
let q = []
18+
for (let i = 0; i < numCourses; i++) {
19+
if (indegree[i] === 0) q.push(i)
20+
}
21+
22+
while (q.length) {
23+
const nxt = []
24+
for (let i = 0, size = q.length; i < size; i++) {
25+
const cur = q[i]
26+
set.add(cur)
27+
for (const e of graph[cur] || []) {
28+
indegree[e]--
29+
if (indegree[e] === 0 && !set.has(e)) {
30+
nxt.push(e)
31+
}
32+
}
33+
}
34+
35+
q = nxt
36+
}
37+
38+
return set.size === numCourses
39+
}
40+
41+
// another
42+
43+
144
/**
245
* @param {number} numCourses
346
* @param {number[][]} prerequisites

0 commit comments

Comments
 (0)