Skip to content

Commit d532715

Browse files
committed
207 js
1 parent a9fdf5d commit d532715

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed

207/main.js

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
/**
2+
* @param {number} numCourses
3+
* @param {number[][]} prerequisites
4+
* @return {boolean}
5+
*/
6+
var canFinish = function(numCourses, prerequisites) {
7+
const indegrees = new Array(numCourses).fill(0)
8+
const c = Array.from({ length: numCourses }, () => new Set())
9+
for (const [from, to] of prerequisites) {
10+
++indegrees[to]
11+
c[from].add(to)
12+
}
13+
const q = new Queue()
14+
for (let i = 0; i < numCourses; i++) {
15+
if (indegrees[i] === 0) {
16+
q.push(i)
17+
}
18+
}
19+
while (!q.empty()) {
20+
const cur = q.top()
21+
q.pop()
22+
for (const to of c[cur]) {
23+
--indegrees[to]
24+
if (indegrees[to] === 0) {
25+
q.push(to)
26+
}
27+
}
28+
}
29+
for (let i = 0; i < numCourses; i++) {
30+
if (indegrees[i]) {
31+
return false
32+
}
33+
}
34+
return true
35+
};
36+
37+
class Queue {
38+
constructor () {
39+
this._front = this._back = { val: null, next: null }
40+
this._length = 0
41+
}
42+
43+
push (val) {
44+
this._back.next = {
45+
val,
46+
next: null
47+
}
48+
this._back = this._back.next
49+
this._length += 1
50+
}
51+
52+
pop () {
53+
if (this._length === 0) {
54+
throw new Error('failed to pop: empty queue')
55+
}
56+
this._length -= 1
57+
this._front = this._front.next
58+
return this._front.val
59+
}
60+
61+
top () {
62+
if (this._length === 0) {
63+
throw new Error('Failed to top: empty queue')
64+
}
65+
return this._front.next.val
66+
}
67+
68+
get length () {
69+
return this._length
70+
}
71+
72+
empty () {
73+
return this._length === 0
74+
}
75+
76+
clear () {
77+
this._front = this._back = { val: null, next: null }
78+
this._length = 0
79+
}
80+
}
81+
82+
if (process.env.LZS) {
83+
console.log(canFinish(2, [[0, 1], [1, 0]]))
84+
console.log(canFinish(2, [[0, 1]]))
85+
}

0 commit comments

Comments
 (0)