-
Notifications
You must be signed in to change notification settings - Fork 129
/
Copy pathCourse Schedule.js
44 lines (40 loc) · 1.14 KB
/
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
/**
* @param {number} numCourses
* @param {number[][]} prerequisites
* @return {boolean}
*/
var constructGraph = function(numNodes, pre) {
var nodes = [];
for (var i = 0; i < numNodes; i++) {
var node = {};
node.neighbors = [];
nodes[i] = node;
}
for (var j = 0; j < pre.length; j++) {
var s = pre[j][1];
var d = pre[j][0];
nodes[s].neighbors.push(nodes[d]);
}
return nodes;
}
// Return true if there is a cycle detected.
var dfs = function(startNode, parents) {
if (parents.indexOf(startNode) >= 0) return true;
if (startNode.visited) return false;
startNode.visited = true;
var neighbors = startNode.neighbors;
parents.push(startNode);
for (var i = 0; i < neighbors.length; i++) {
var hasCycle = dfs(neighbors[i], parents);
if (hasCycle) return true;
}
parents.pop();
}
var canFinish = function(numCourses, prerequisites) {
var nodes = constructGraph(numCourses, prerequisites);
for (var i = 0; i < nodes.length; i++) {
var hasCycle = dfs(nodes[i], []);
if (hasCycle) return false;
}
return true;
};