| 2 | // time O(v + e) | O(v) space - where v is the number of vertices and e the number of edges in the graph |
| 3 | |
| 4 | function cycleInGraph(edges) { |
| 5 | const numberOfNodes = edges.length; |
| 6 | const visitedVetices = new Array(numberOfNodes).fill(false); |
| 7 | const inStack = new Array(numberOfNodes).fill(false); |
| 8 | |
| 9 | for (let node = 0; node < numberOfNodes; node++) { |
| 10 | if (visitedVetices[node]) continue; |
| 11 | const containsCycle = DFS(node, edges, visitedVetices, inStack); |
| 12 | if (containsCycle) return true; |
| 13 | } |
| 14 | return false; |
| 15 | } |
| 16 | |
| 17 | function DFS(node, edges, visitedVertices, inStack) { |
| 18 | visitedVertices[node] = true; |