public void TestAlgorthim() { MemoizationTable memoTable = new MemoizationTable(); Vertex initialVertex = new Vertex(); Vertex secondaryVertex = new Vertex(); Vertex tertiaryVertex = new Vertex(); Vertex quaternaryVertex = new Vertex(); initialVertex.AddEdgeTowardsOtherVertex(secondaryVertex, 3); initialVertex.AddEdgeTowardsOtherVertex(tertiaryVertex, 15); secondaryVertex.AddEdgeTowardsOtherVertex(tertiaryVertex, 7); secondaryVertex.AddEdgeTowardsOtherVertex(quaternaryVertex, 4); tertiaryVertex.AddEdgeTowardsOtherVertex(initialVertex, 1); tertiaryVertex.AddEdgeTowardsOtherVertex(secondaryVertex, 1); tertiaryVertex.AddEdgeTowardsOtherVertex(tertiaryVertex, 1); tertiaryVertex.AddEdgeTowardsOtherVertex(quaternaryVertex, 1); memoTable.AddVertex(initialVertex); memoTable.AddVertex(secondaryVertex); memoTable.AddVertex(tertiaryVertex); memoTable.AddVertex(quaternaryVertex); memoTable.CalculateShortestPath(initialVertex); Assert.Equal(0, memoTable.ShortestPathsTable.FirstOrDefault(x => x.Vertex == initialVertex).LowestCostPath); Assert.Equal(3, memoTable.ShortestPathsTable.FirstOrDefault(x => x.Vertex == secondaryVertex).LowestCostPath); Assert.Equal(10, memoTable.ShortestPathsTable.FirstOrDefault(x => x.Vertex == tertiaryVertex).LowestCostPath); Assert.Equal(7, memoTable.ShortestPathsTable.FirstOrDefault(x => x.Vertex == quaternaryVertex).LowestCostPath); }
/// <summary> /// Extension method to calculate shortest paths using Dijkstra's Algorithm. /// </summary> /// <param name="memoTable">Memoization Table</param> /// <param name="vertex">Vertex To calculate path from</param> /// <returns>Updated memoization table</returns> public static MemoizationTable CalculateShortestPath(this MemoizationTable memoTable, Vertex vertex) { memoTable.Update(vertex, 0); int costToCurrentVertex = 0; // TODO: swap out infinite loop while (true) { // initialise edge Edge smallestEdgeToUnvisitedVertex = null; // Find lowest weighted edge to an unvisited vertex from current vertex bool changed = false; foreach (Edge edge in vertex.GetDirectedEdges().Where(x => !x.DirectedTo.Visited)) { memoTable.Update(edge.DirectedTo, costToCurrentVertex + edge.Weight); if ((smallestEdgeToUnvisitedVertex == null) || (edge.Weight < smallestEdgeToUnvisitedVertex.Weight)) { smallestEdgeToUnvisitedVertex = edge; changed = true; } } if (changed == false) { // All vertices visited break; } // Visit nearest unvisited vertex with smallest cost vertex = smallestEdgeToUnvisitedVertex.DirectedTo; costToCurrentVertex += smallestEdgeToUnvisitedVertex.Weight; } return(memoTable); }