private TSPSolution solve(TSPInput input, bool hasEdge = false, int startNode = 0, int endNode = 0) { TSPSolution result = null; if (hasEdge) { result = new TSPSolutionPath(input, startNode, endNode); } else { result = new TSPSolution(input); } succ = new List <List <int> >(); edge predefinedEdge = default; edgesUsed = 0; List <edge> edges = new List <edge>(); for (int i = 0; i < input.nodesCount; i++) { succ.Add(new List <int>()); for (int j = 0; j < i; j++) { edge ed = new edge(i, j, input.getDistance(i, j)); if (hasEdge && (startNode == i && endNode == j) || (startNode == j && endNode == i)) { predefinedEdge = ed; } else { edges.Add(ed); } } } if (hasEdge) { addToSolution(predefinedEdge); } edges.Sort((a, b) => (int)(a.distance - b.distance)); int index = -1; while (edgesUsed < input.nodesCount) { index++; edge e = edges[index]; if (succ[e.node1].Count >= 2 || succ[e.node2].Count >= 2) { continue; } if (createsCycle(e) && edgesUsed != input.nodesCount - 1) { continue; } addToSolution(e); } addEdgesToResult(result); return(result); }
public override TSPSolution solvePath(TSPInput input, int startNode, int endNode) { available.Clear(); for (int i = 0; i < input.nodesCount; i++) { available.Add(i); } TSPSolution result = new TSPSolutionPath(input, startNode, endNode); int j = startNode; available.Remove(startNode); available.Remove(endNode); result.setSuccessor(endNode, startNode); for (int i = 0; i < input.nodesCount - 2; i++) { int best = findBest(j, input); result.setSuccessor(j, best); j = best; available.Remove(best); } result.setSuccessor(j, endNode); return(result); }