-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstructy-068-prereqsPossible.js
78 lines (63 loc) · 1.48 KB
/
structy-068-prereqsPossible.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
74
75
76
77
78
// https://structy.net/problems/premium/prereqs-possible
// p: num+, arr
// r: boolean
const prereqsPossible = (numCourses, prereqs) => {
const graph = buildGraph(prereqs);
const visited = new Set();
for (const node in graph) {
if (checkCycle(graph, node, visited, new Set())) return false;
}
return true;
};
const checkCycle = (graph, node, visited, visiting) => {
if (visited.has(+node)) return false;
if (visiting.has(+node)) return true;
visiting.add(+node);
for (const nei of graph[+node]) {
if (checkCycle(graph, nei, visited, visiting)) return true;
}
visiting.delete(+node);
visited.add(+node);
return false;
};
const buildGraph = (edges) => {
const graph = {};
for (const edge of edges) {
const [a, b] = edge;
!(a in graph) && (graph[a] = []);
!(b in graph) && (graph[b] = []);
graph[a].push(b);
// graph[b].push(a); WRONG because only 1 WAY
}
return graph;
};
// { '0': [ 1, 2 ], '1': [ 3 ], '2': [ 3 ], '3': [], '4': [ 5 ], '5': [] }
// visited: 0 1 2 3
// visiting: 4 5
// 0 --> 1
// | |
// 2 --> 3
// 4 --> 5
const numCourses = 6;
const prereqs = [
[0, 1],
[2, 3],
[0, 2],
[1, 3],
[4, 5],
];
console.log(prereqsPossible(numCourses, prereqs)); // -> true
// const numCourses = 6;
// const prereqs = [
// [0, 1],
// [2, 3],
// [0, 2],
// [1, 3],
// [4, 5],
// [3, 0],
// ];
// // 0 --> 1
// // | \ |
// // 2 --> 3
// // 4 --> 5
// console.log(prereqsPossible(numCourses, prereqs)); // -> false