-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path210. Course Schedule II(DFS).js
73 lines (65 loc) · 1.65 KB
/
210. Course Schedule II(DFS).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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
* Note:
* 1. Node to use HashMap(child, parent) to build the graph
* 2. put parent in the result
*/
'use strict';
/**
* @param {number} numCourses
* @param {number[][]} prerequisites
* @return {number[]}
*/
var findOrder = function(numCourses, prerequisites) {
let result = new Array();
if (numCourses === 0) {
return [0];
}
if (prerequisites.length === 0 || prerequisites[0].length === 0) {
for (let i = 0; i < numCourses; i++) {
result.unshift(i);
}
return result;
}
if (prerequisites === null) {
throw new Error('illegal argument exception!');
}
let length = prerequisites.length;
let graph = new Map();
let visited = new Array(numCourses).fill(0);
//Build graph
for (let edges of prerequisites) {
if (graph.has(edges[0])) {
graph.get(edges[0]).push(edges[1]);
} else {
let parent = new Array();
parent.push(edges[1]);
graph.set(edges[0], parent);
}
}
for (let i = 0; i < numCourses; i++) {
if (dfs(i)) {
// console.log('hello');
return [];
}
}
return result;
/*
* @param {number} iteration index
* @return {boolean} has loop or not
*/
function dfs(node) {
if (visited[node] === -1) return false;
if (visited[node] === 1) return true;
visited[node] = 1;
if (graph.has(node)) {
for (let parent of graph.get(node)) {
if (dfs(parent)) {
return true;
}
}
}
visited[node] = -1;
result.push(node);
return false;
}
};