private static List <int> CalculateFinishingTimes(IDirectedGraphWithReversed <int> graph) { var finishedVertices = new List <int>(); var exploredVertices = new HashSet <int>(); foreach (int v in graph.GetVertices()) { if (!exploredVertices.Contains(v)) { DfsCalculateFinishingTimes(graph, v, exploredVertices, finishedVertices); } } return(finishedVertices); }
private static void DfsCalculateFinishingTimes(IDirectedGraphWithReversed <int> graph, int startVertex, HashSet <int> exploredVertices, List <int> finishedVertices) { var stack = new Stack <int>(); stack.Push(startVertex); while (stack.Any()) { int v = stack.Peek(); if (!exploredVertices.Contains(v)) { exploredVertices.Add(v); } bool hasUnexploredNeighbours = false; foreach (int w in graph.GetIncomingVertices(v)) { if (!exploredVertices.Contains(w)) { hasUnexploredNeighbours = true; stack.Push(w); break; } } if (hasUnexploredNeighbours) { continue; } finishedVertices.Add(stack.Pop()); } }
public static List <List <int> > FindStronglyConnectedComponents(IDirectedGraphWithReversed <int> graph) { List <int> finishingTimesVertices = CalculateFinishingTimes(graph); return(ComputeStronglyConnectedComponents(graph, finishingTimesVertices)); }