Last active
February 14, 2022 02:52
-
-
Save svaza/6d205802a41d7a80c4cf21237bfc48b1 to your computer and use it in GitHub Desktop.
Directed Graph - Detect Cycle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export function cycleInGraph(edges: number[][]) { | |
| // 1. loop through all vertices of the graph | |
| for (let v = 0; v < edges.length; v++) { | |
| if (hasCycle(edges, v, new Set<Number>())) | |
| return true; | |
| } | |
| return false; | |
| } | |
| /** | |
| * Checks whether there is a cycle for the given vertex | |
| * Implements DFS approach for iterating over the adj vertices | |
| * @param adjList Adjacency list or Graph | |
| * @param v The current vertex | |
| * @param visited Visited stack | |
| * @returns | |
| */ | |
| function hasCycle(adjList: number[][], v: number, visited: Set<Number>): boolean { | |
| // 4. if the current vertex was visited earlier in the stack then it means that | |
| // there is a cycle | |
| if(visited.has(v)) return true; | |
| // 3. Think of the visited set as a current stack where we add the | |
| // current vertex in the set before begining DFS over it | |
| else visited.add(v); | |
| // 2. loop through all adjacent vertices of the current vertex | |
| for(let adjV of adjList[v]) { | |
| if(hasCycle(adjList, adjV, visited)) { | |
| return true; | |
| } | |
| } | |
| // 5. remove the current vertex from the stack | |
| visited.delete(v); | |
| return false; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment