-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstructy-067-hasCycle-2.js
62 lines (52 loc) · 991 Bytes
/
structy-067-hasCycle-2.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
// p: obj
// r: boolean
// e:
// hasCycle({
// a: ["b"],
// b: ["c"],
// c: ["a"],
// }); // -> true
// a -> b
// ^ |
// \ v
// c
// o x x x
// a -> b -> d -> e -> f
// ^ |
// \ v
// c o
const hasCycle = (graph) => {
const visited = new Set();
// traversal from each node and mark visited
for (let node in graph) {
if (explore(graph, node, visited)) return true;
}
return false;
};
const explore = (graph, node, visited, visiting = new Set()) => {
if (visited.has(node)) return false;
if (visiting.has(node)) return true;
visiting.add(node);
for (let nei of graph[node]) {
if (explore(graph, nei, visited, visiting)) return true;
}
visited.add(node);
return false;
};
console.log(
hasCycle({
a: ["b", "c"],
b: [],
c: [],
e: ["f"],
f: ["e"],
})
); // -> true
// console.log(
// hasCycle({
// a: ["b", "c"],
// b: ["c"],
// c: ["d"],
// d: [],
// })
// ); // -> false