public ShortestPathsTree Run(Node startNode) { _result = InitializeShortestPathTree(startNode); var iterations = 0; while (_result.TryGetShortestPathNotYetRelaxed(out Path shortestNoneRelaxedPath)) { _result = RelaxNode(shortestNoneRelaxedPath.EndNode); iterations++; } return(_result); }
private ShortestPathsTree RelaxResult(ShortestPathsTree result, Node from, Connection to) { var pathToEndPoint = result.Paths.Single(r => r.EndNode == to.Node); var pathToFrom = result.Paths.Single(r => r.EndNode == from); var currentPathCost = pathToEndPoint.Cost; var costWithAdditionalNode = pathToFrom.Cost.Add(to.Cost); if (currentPathCost > costWithAdditionalNode) { pathToEndPoint.Relax(pathToFrom, to); } return(result); }
public static bool TryGetShortestPathNotYetRelaxed(this ShortestPathsTree result, out Path path) { if (result == null || result.Paths.IsEmpty()) { path = default; return(false); } var paths = result.Paths .Where(r => !r.IsRelaxed); var min = paths .Select(r => r.Cost) .MinOrDefault(); path = paths.FirstOrDefault(p => p.Cost == min); return(path != null); }