-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
85 lines (77 loc) · 1.6 KB
/
Copy pathmain.js
File metadata and controls
85 lines (77 loc) · 1.6 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/**
* @param {number} numCourses
* @param {number[][]} prerequisites
* @return {boolean}
*/
var canFinish = function(numCourses, prerequisites) {
const indegrees = new Array(numCourses).fill(0)
const c = Array.from({ length: numCourses }, () => new Set())
for (const [from, to] of prerequisites) {
++indegrees[to]
c[from].add(to)
}
const q = new Queue()
for (let i = 0; i < numCourses; i++) {
if (indegrees[i] === 0) {
q.push(i)
}
}
while (!q.empty()) {
const cur = q.top()
q.pop()
for (const to of c[cur]) {
--indegrees[to]
if (indegrees[to] === 0) {
q.push(to)
}
}
}
for (let i = 0; i < numCourses; i++) {
if (indegrees[i]) {
return false
}
}
return true
};
class Queue {
constructor () {
this._front = this._back = { val: null, next: null }
this._length = 0
}
push (val) {
this._back.next = {
val,
next: null
}
this._back = this._back.next
this._length += 1
}
pop () {
if (this._length === 0) {
throw new Error('failed to pop: empty queue')
}
this._length -= 1
this._front = this._front.next
return this._front.val
}
top () {
if (this._length === 0) {
throw new Error('Failed to top: empty queue')
}
return this._front.next.val
}
get length () {
return this._length
}
empty () {
return this._length === 0
}
clear () {
this._front = this._back = { val: null, next: null }
this._length = 0
}
}
if (process.env.LZS) {
console.log(canFinish(2, [[0, 1], [1, 0]]))
console.log(canFinish(2, [[0, 1]]))
}