-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstructy-067-hasCycle.js
78 lines (61 loc) · 1.49 KB
/
structy-067-hasCycle.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/has-cycle
// p: obj (graph)
// r: boolean
const hasCycle = (graph) => {
const visited = new Set();
const visiting = new Set();
for (const node in graph) {
if (cycleDetect(graph, node, visited, visiting)) return true;
}
return false;
};
const cycleDetect = (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 (cycleDetect(graph, nei, visited, visiting)) {
return true;
}
}
visited.add(nei);
visiting.remove(nei);
return false;
};
// iteration NOT WORKING
// const hasCycle = (graph) => {
// const visited = new Set();
// for (const node in graph) {
// if (visited.has(node)) continue;
// const stack = [node];
// const visiting = new Set();
// visiting.add(node);
// while (stack.length > 0) {
// const current = stack.pop();
// for (const nei of graph[current]) {
// if (visiting.has(nei) && !visited.has(nei)) return true;
// visiting.add(nei);
// stack.push(nei);
// if (graph[nei].length === 0) visited.add(nei);
// }
// }
// }
// return false;
// };
console.log(
hasCycle({
a: ["b"],
b: ["c"],
c: ["a"],
})
);
// // -> true
console.log(
hasCycle({
a: ["b", "c"],
b: ["c"],
c: ["d"],
d: [],
})
);
// -> false