-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path207.课程表.js
56 lines (51 loc) · 1.22 KB
/
207.课程表.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
54
55
56
/*
* @lc app=leetcode.cn id=207 lang=javascript
*
* [207] 课程表
*/
const { map } = require('async')
// @lc code=start
/**
* @param {number} numCourses
* @param {number[][]} prerequisites
* @return {boolean}
*/
// tips: use directed graph to solve
var canFinish = function(numCourses, prerequisites) {
const graph = buildGraph(numCourses, prerequisites)
let hasCycle = false
const visited = []
const onPath = []
// has no single start point
for (let i = 0; i < numCourses; i++) {
traverse(graph, i)
}
return !hasCycle
function traverse(graph, start) {
if (onPath[start]) {
hasCycle = true
}
if (visited[start] || hasCycle) {
return
}
onPath[start] = true
visited[start] = true
const neighbors = graph[start]
neighbors.forEach(neighbor => {
traverse(graph, neighbor)
})
onPath[start] = false
visited[start] = false
}
function buildGraph(numCourses, prerequisites) {
const graph = new Array(numCourses).fill(0).map(c => new Array().fill([]))
prerequisites.forEach(prereq => {
const from = prereq[0]
const to = prereq[1]
graph[from].push(to)
})
return graph
}
}
// @lc code=end
module.exports = { canFinish }