-
Notifications
You must be signed in to change notification settings - Fork 299
/
Copy pathCycleDetection.cs
48 lines (38 loc) · 1.25 KB
/
CycleDetection.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System.Collections.Generic;
using Advanced.Algorithms.DataStructures.Graph;
namespace Advanced.Algorithms.Graph;
/// <summary>
/// Cycle detection using Depth First Search.
/// </summary>
public class CycleDetector<T>
{
/// <summary>
/// Returns true if a cycle exists
/// </summary>
public bool HasCycle(IDiGraph<T> graph)
{
var visiting = new HashSet<T>();
var visited = new HashSet<T>();
foreach (var vertex in graph.VerticesAsEnumberable)
if (!visited.Contains(vertex.Key))
if (Dfs(vertex, visited, visiting))
return true;
return false;
}
private bool Dfs(IDiGraphVertex<T> current,
HashSet<T> visited, HashSet<T> visiting)
{
visiting.Add(current.Key);
foreach (var edge in current.OutEdges)
{
//if we encountered a visiting vertex again
//then their is a cycle
if (visiting.Contains(edge.TargetVertexKey)) return true;
if (visited.Contains(edge.TargetVertexKey)) continue;
if (Dfs(edge.TargetVertex, visited, visiting)) return true;
}
visiting.Remove(current.Key);
visited.Add(current.Key);
return false;
}
}