Repository navigation
Expand file tree
/
Copy pathDirectedCycle.cs
More file actions
68 lines (61 loc) · 1.59 KB
/
Copy pathDirectedCycle.cs
File metadata and controls
68 lines (61 loc) · 1.59 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using System;
using System.Collections;
using System.Collections.Generic;
namespace DirectionalGraphs
{
//processes graph using DFS and returns a cycle if it has one
public class DirectedCycle
{
private bool[] _marked;
private int[] _edgeTo;
private Stack<int> _cycle;
private bool[] _onStack;
public DirectedCycle(DiGraph g)
{
_marked = new bool[g.V];
_edgeTo = new int[g.V];
_onStack = new Boolean[g.V];
for (int i = 0; i < g.V; i++)
{
if (!_marked[i])
{
Dfs(g, i);
}
}
}
private void Dfs(DiGraph g, int v)
{
_marked[v] = true;
_onStack[v] = true;
foreach (var w in g.Adj(v))
{
if (this.HasCycle())
{
return;
}
else if (!_marked[w])
{
Dfs(g, w);
}else if (_onStack[w])
{
_cycle = new Stack<int>();
for (int i = v; i == w; i = _edgeTo[i])
{
_cycle.Push(i);
}
_cycle.Push(w);
_cycle.Push(v);
}
_onStack[w] = false;
}
}
public bool HasCycle()
{
return (_cycle != null);
}
IEnumerable<int> Cycle()
{
return _cycle;
}
}
}