public static IReadOnlyList <double> ShortestPaths(GraphWithTracking graph, int startingVertex) { graph.CalculatedDistance[startingVertex] = 0; for (var i = 0; i < graph.NumberOfVertices - 1; i++) { var unvisitedVertexWithShortestDistance = graph.Verteces .Where(_ => !graph.IsVisited[_]) .Aggregate( (aggregateVertex, currentVertex) => graph.CalculatedDistance[aggregateVertex] < graph.CalculatedDistance[currentVertex] ? aggregateVertex : currentVertex); graph.IsVisited[unvisitedVertexWithShortestDistance] = true; var distance = graph.CalculatedDistance[unvisitedVertexWithShortestDistance]; for (var j = 0; j < graph.NumberOfVertices; j++) { var newRelaxedDistance = distance + graph[unvisitedVertexWithShortestDistance, j]; if (graph.CalculatedDistance[j] > newRelaxedDistance) { graph.CalculatedDistance[j] = newRelaxedDistance; } } } return(graph.CalculatedDistance.ToList()); }
public static IReadOnlyList <double> ShortestPaths(GraphWithTracking graph, int startingVertex) { graph.CalculatedDistance[startingVertex] = 0; var finiteDistances = graph.AsEnumerable() .Where(_ => !double.IsPositiveInfinity(_.weight)) .ToList(); for (var currentVertex = 0; currentVertex < graph.NumberOfVertices; currentVertex++) { for (var currentEdge = 0; currentEdge < graph.NumberOfEdges; currentEdge++) { var newRelaxedDistance = graph.CalculatedDistance[finiteDistances[currentEdge].fromVertex] + finiteDistances[currentEdge].weight; if (graph.CalculatedDistance[finiteDistances[currentEdge].toVertex] > newRelaxedDistance) { graph.CalculatedDistance[finiteDistances[currentEdge].toVertex] = newRelaxedDistance; } } } for (var currentEdge = 0; currentEdge < graph.NumberOfEdges; currentEdge++) { var newRelaxedDistance = graph.CalculatedDistance[finiteDistances[currentEdge].fromVertex] + finiteDistances[currentEdge].weight; if (graph.CalculatedDistance[finiteDistances[currentEdge].toVertex] > newRelaxedDistance) { graph.CalculatedDistance[finiteDistances[currentEdge].toVertex] = double.NegativeInfinity; } } return(graph.CalculatedDistance.ToList()); }