-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGraph.DetectCycle.cs
34 lines (30 loc) · 1.02 KB
/
Graph.DetectCycle.cs
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
// DFS
public class Solution {
public void DetectCycle(int[][] edges, int n) {
//Create adjacency List
List[] adj = new List[n];
foreach(var edge in edges){
//if not exist add
if(adj[edge[0]] == null)
adj[edge[0]] = new List();
if(adj[edge[1]] == null)
adj[edge[1]] = new List();
//add edges in the adj list
adj[edge[0]].Add(edge[1]);
adj[edge[1]].Add(edge[0]);
}
Stack<(int, int)> stack = new Stack<(int, int)>();
HashSet<int> visited = new HashSet<int>();
while(stack.Count > 0){
var (node, parent) = stack.Pop();
visited.Add(node);
foreach(var neighbor in adj[node]){
if(visited.Contains(neighbor) && neighbor != parent)
return true;
if(!visited.Contains(neighbor))
stack.Push((neighbor, node));
}
}
return false;
}
}