-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhasCycle.js
44 lines (35 loc) · 1023 Bytes
/
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
// Write a function, hasCycle, that takes in an object representing the adjacency list of a directed graph. The function should return a boolean indicating whether or not the graph contains a cycle.
const hasCycle = (graph) => {
const visiting = new Set()
const visited = new Set()
for(let node in graph){
if(cycleDetect(graph, node, visiting, visited) === true){
return true
}
}
return false
};
const cycleDetect = (graph, node, visiting, visited) => {
if(visited.has(node)) return false
if(visiting.has(node)) return true // there is a cycle
visiting.add(node)
for(let neighbor of graph[node]){
if(cycleDetect(graph, neighbor, visiting, visited) === true){
return true
}
}
visiting.delete(node)
visited.add(node)
return false
}
hasCycle({
a: ["b"],
b: ["c"],
c: ["a"],
}); // -> true
hasCycle({
a: ["b", "c"],
b: ["c"],
c: ["d"],
d: [],
}); // -> false