【发布时间】:2017-01-06 14:54:07
【问题描述】:
我在Wikipedia 之后在 Java 中实现了 Held-Karp,它为循环的总距离提供了正确的解决方案,但是我需要它来给我路径(它不会在开始的同一个顶点上结束) .如果我从循环中取出重量最大的边缘,我可以获得路径,但是有可能2个不同的循环具有相同的总距离,但最大重量不同,因此其中一个循环是错误的。
这是我的实现:
//recursion is called with tspSet = [0, {set of all other vertices}]
private static TSPSet recursion (TSPSet tspSet) {
int end = tspSet.endVertex;
HashSet<Integer> set = tspSet.verticesBefore;
if (set.isEmpty()) {
TSPSet ret = new TSPSet(end, new HashSet<>());
ret.secondVertex = -1;
ret.totalDistance = matrix[end][0];
return ret;
}
int min = Integer.MAX_VALUE;
int minVertex = -1;
HashSet<Integer> copy;
for (int current: set) {
copy = new HashSet<>(set);
copy.remove(current);
TSPSet candidate = new TSPSet(current, copy);
int distance = matrix[end][current] + recursion(candidate).totalDistance;
if (distance < min) {
min = distance;
minVertex = current;
}
}
tspSet.secondVertex = minVertex;
tspSet.totalDistance = min;
return tspSet;
}
class TSPSet {
int endVertex;
int secondVertex;
int totalDistance;
HashSet<Integer> verticesBefore;
public TSPSet(int endVertex, HashSet<Integer> vertices) {
this.endVertex = endVertex;
this.secondVertex = -1;
this.verticesBefore = vertices;
}
}
【问题讨论】:
标签: java algorithm traveling-salesman