public void Dijikstra_Smoke_Test() { var graph = new WeightedDiGraph <char, int>(); graph.AddVertex('S'); graph.AddVertex('A'); graph.AddVertex('B'); graph.AddVertex('C'); graph.AddVertex('D'); graph.AddVertex('T'); graph.AddEdge('S', 'A', 8); graph.AddEdge('S', 'C', 10); graph.AddEdge('A', 'B', 10); graph.AddEdge('A', 'C', 1); graph.AddEdge('A', 'D', 8); graph.AddEdge('B', 'T', 4); graph.AddEdge('C', 'D', 1); graph.AddEdge('D', 'B', 1); graph.AddEdge('D', 'T', 10); var algorithm = new DijikstraShortestPath <char, int>(new DijikstraShortestPathOperators()); var result = algorithm.GetShortestPath(graph, 'S', 'T'); Assert.AreEqual(15, result.Length); var expectedPath = new char[] { 'S', 'A', 'C', 'D', 'B', 'T' }; for (int i = 0; i < expectedPath.Length; i++) { Assert.AreEqual(expectedPath[i], result.Path[i]); } }
GetAllPairShortestPaths(WeightedDiGraph <T, W> graph) { var workGraph = graph.Clone(); //add an extra vertex with zero weight edge to all nodes var randomVetex = operators.RandomVertex(); if (workGraph.Vertices.ContainsKey(randomVetex)) { throw new Exception("Random Vertex is not unique for given graph."); } workGraph.AddVertex(randomVetex); foreach (var vertex in workGraph.Vertices) { workGraph.AddEdge(randomVetex, vertex.Key, operators.DefaultValue); } //now compute shortest path from random vertex to all other vertices var bellmanFordSP = new BellmanFordShortestPath <T, W>(operators); var bellFordResult = new Dictionary <T, W>(); foreach (var vertex in workGraph.Vertices) { var result = bellmanFordSP.GetShortestPath(workGraph, randomVetex, vertex.Key); bellFordResult.Add(vertex.Key, result.Length); } //adjust edges so that all edge values are now +ive foreach (var vertex in workGraph.Vertices) { foreach (var edge in vertex.Value.OutEdges.ToList()) { vertex.Value.OutEdges[edge.Key] = operators.Substract( operators.Sum(bellFordResult[vertex.Key], edge.Value), bellFordResult[edge.Key.Value]); } } workGraph.RemoveVertex(randomVetex); //now run dijikstra for all pairs of vertices //trace path var dijikstras = new DijikstraShortestPath <T, W>(operators); var finalResult = new List <AllPairShortestPathResult <T, W> >(); foreach (var vertexA in workGraph.Vertices) { foreach (var vertexB in workGraph.Vertices) { var source = vertexA.Key; var dest = vertexB.Key; var sp = dijikstras.GetShortestPath(workGraph, source, dest); //no path exists if (sp.Length.Equals(operators.MaxValue)) { continue; } var distance = sp.Length; var path = sp.Path; finalResult.Add(new AllPairShortestPathResult <T, W>(source, dest, distance, path)); } } return(finalResult); }