public void PostOrderTest() { var graph = new Graph(); graph.Nodes.Add("0"); graph.Nodes.Add("1"); graph.Nodes.Add("2"); graph.Nodes.Add("3"); graph.Nodes.Add("4"); graph.Edges.Add("0", "2"); graph.Edges.Add("2", "1"); graph.Edges.Add("1", "0"); graph.Edges.Add("0", "3"); graph.Edges.Add("3", "4"); var traversal = new DepthFirstTraversal(); var recorder = new PostOrderRecorder(traversal); traversal.Run(graph.Nodes["0"]); var order = recorder.GetOrder(); Assert.Equal(order.Count, graph.Nodes.Count); Assert.All(graph.Nodes, n => Assert.True(order.IndexOf(graph.Nodes["0"]) >= order.IndexOf(n))); Assert.True(order.IndexOf(graph.Nodes["1"]) < order.IndexOf(graph.Nodes["2"])); Assert.True(order.IndexOf(graph.Nodes["4"]) < order.IndexOf(graph.Nodes["3"])); }
public static ICollection <ISet <Node> > FindStronglyConnectedComponents(this Node entrypoint) { var graph = entrypoint.ParentGraph; var traversal = new DepthFirstTraversal(); var recorder = new PostOrderRecorder(traversal); traversal.Run(entrypoint); var transpose = graph.Transpose(); var visited = new HashSet <Node>(); var result = new List <ISet <Node> >(); foreach (var node in recorder.GetOrder().Reverse()) { if (!visited.Contains(node)) { var subTraversal = new DepthFirstTraversal(); var component = new HashSet <Node>(); subTraversal.NodeDiscovered += (sender, args) => { if (visited.Add(graph.Nodes[args.NewNode.Name])) { args.ContinueExploring = true; component.Add(graph.Nodes[args.NewNode.Name]); } }; subTraversal.Run(transpose.Nodes[node.Name]); result.Add(component); } } return(result); }