public double SolveExternalClusters(CostMatrix costMatrix, List<CityNodeData> CityData, List<CityCluster> cityClusters, Dictionary<int, CityCluster> cityToClusterItsIn, out List<int> interNodeEdges) { int startingEdge = -1; foreach (int i in costMatrix.AllEdgesSortedByDistance) { KeyValuePair<int, int> coords = costMatrix.EdgeCoords(i); if (!cityToClusterItsIn[coords.Key].Equals(cityToClusterItsIn[coords.Value])) { startingEdge = i; break; } } KeyValuePair<int, int> curCoords = costMatrix.EdgeCoords(startingEdge); CityCluster curFromCluster = cityToClusterItsIn[curCoords.Key]; List<int> visitedCities = new List<int>(); List<CityCluster> clustersVisitedInOrder = new List<CityCluster>(); interNodeEdges = new List<int>(); clustersVisitedInOrder.Add(cityToClusterItsIn[curCoords.Key]); visitedCities.AddRange(cityToClusterItsIn[curCoords.Key].ContainedCityIds); cityToClusterItsIn[curCoords.Value].IncomingFromEdge(startingEdge); cityToClusterItsIn[curCoords.Key].OutgoingOnEdge(startingEdge); interNodeEdges.Add(startingEdge); while (interNodeEdges.Count < cityClusters.Count - 1) { curFromCluster = cityToClusterItsIn[curCoords.Value]; int newEdgeId = curFromCluster.GetShortestValidOutgoingEdgeIgnoringCities(visitedCities); curCoords = costMatrix.EdgeCoords(newEdgeId); cityToClusterItsIn[curCoords.Value].IncomingFromEdge(newEdgeId); cityToClusterItsIn[curCoords.Value].OutgoingOnEdge(newEdgeId); clustersVisitedInOrder.Add(curFromCluster); visitedCities.AddRange(curFromCluster.ContainedCityIds); interNodeEdges.Add(newEdgeId); } CityCluster end = cityToClusterItsIn[curCoords.Value]; CityCluster start = clustersVisitedInOrder[0]; int lastEdge = CityCluster.ShortedValidEdgeBetweenClusters(end, start); interNodeEdges.Add(lastEdge); _interNodeEdges = interNodeEdges; double retVal = 0; foreach (int edge in interNodeEdges) { retVal += costMatrix.CostAtEdgeId(edge); } return retVal; }
private TSPSolution Solve(CostMatrix costMatrix, List<CityNodeData> CityData, List<CityCluster> cityClusters, Dictionary<int, CityCluster> cityToClusterItsIn, List<int> interNodeEdges) { List<int> allEdges = new List<int>(); ArrayList sol = new ArrayList(); foreach (int edge in interNodeEdges) { KeyValuePair<int, int> coords = costMatrix.EdgeCoords(edge); CityCluster target = cityToClusterItsIn[coords.Value]; allEdges.Add(edge); List<int> edgesSolved = target.GreedySolveEdges(); if (edgesSolved.Count == 0) { sol.Add(Cities[target.ContainedCityIds[0]]); } else { for (int i = 0; i < edgesSolved.Count; i++) { int curEdge = edgesSolved[i]; KeyValuePair<int, int> innerCoords = costMatrix.EdgeCoords(curEdge); if (i == 0) { sol.Add(Cities[innerCoords.Key]); } sol.Add(Cities[innerCoords.Value]); allEdges.Add(curEdge); } } } return new TSPSolution(sol); }