Aquí hay una implementación de C# en funcionamiento de la detección de ciclo de tarjan.Ayuda de detección de ciclo de Tarjan C#
El algoritmo se encuentra aquí: 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);
}
}
Nota a DepGraph es sólo una lista de vértice. y Vertex tiene una lista de otros vértices que representan los bordes. También el índice y el enlace bajo se inicializan en -1
EDITAR: Esto está funcionando ... Acabo de malinterpretar los resultados.
¿Por qué 'v.lowlink = Math.Min (v.lowlink, w.index)' que no sea 'v.lowlink = Math.Min (v.lowlink, w.lowlink)'? –
@LinMa Cualquiera es técnicamente correcto. –