यहां तर्जन के चक्र का पता लगाने का एक सी # कार्यान्वयन है।तर्जन चक्र पहचान सहायता सी #
एल्गोरिथ्म यहाँ पाया जाता है: http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
public class TarjanCycleDetect
{
private static List<List<Vertex>> StronglyConnectedComponents;
private static Stack<Vertex> S;
private static int index;
private static DepGraph dg;
public static List<List<Vertex>> DetectCycle(DepGraph g)
{
StronglyConnectedComponents = new List<List<Vertex>>();
index = 0;
S = new Stack<Vertex>();
dg = g;
foreach (Vertex v in g.vertices)
{
if (v.index < 0)
{
strongconnect(v);
}
}
return StronglyConnectedComponents;
}
private static void strongconnect(Vertex v)
{
v.index = index;
v.lowlink = index;
index++;
S.Push(v);
foreach (Vertex w in v.dependencies)
{
if (w.index < 0)
{
strongconnect(w);
v.lowlink = Math.Min(v.lowlink, w.lowlink);
}
else if (S.Contains(w))
{
v.lowlink = Math.Min(v.lowlink, w.index);
}
}
if (v.lowlink == v.index)
{
List<Vertex> scc = new List<Vertex>();
Vertex w;
do
{
w = S.Pop();
scc.Add(w);
} while (v != w);
StronglyConnectedComponents.Add(scc);
}
}
नोट एक DepGraph सिर्फ वर्टेक्स की एक सूची है। और वेरटेक्स में अन्य वेरटेक्स की एक सूची है जो किनारों का प्रतिनिधित्व करती है। इसके अलावा इंडेक्स और लोलिंक को -1
संपादित करें: यह काम कर रहा है ... मैंने अभी परिणामों का गलत व्याख्या किया है।
यह v.lowlink = Math.Min (v.lowlink, w.index) 'v.lowlink = Math.Min (v.lowlink, w.lowlink) 'के अलावा क्यों है? –
@LinMa या तो तकनीकी रूप से सही है। –