我被困在学校项目的这一部分,我必须得到两个坐标之间的最短路线(旅行推销员问题)。我在这里做了一点东西来获得最近邻居的共同利益,但有几个共同利益集团有相同的最近邻居,我不想要这样的情况。
我想出了一些方法来解决这个问题,但它不起作用,而且我也不知道为什么。
distance
是当前位置与其他位置之间的当前距离。我认为shortestDistance
在某种程度上是不言而喻的。
locations[20][3]
是一个2D数组,我在其中存储了Xco-ord、Yco-ord和每个co-ord的最近邻居。x在x中,Y在x中,邻居在x中
for(int i = 0; i < 20; i++){
int shortestDistance = 100;
int distance;
//Looking for nearest neighbour 20 times
for(int j = 0; j < 20; j++){
//Looking for the closest neighbour here
distanceX = locations[i][0] - locations[j][0];
distanceY = locations[i][1] - locations[j][1];
//To prevent a negative distance:
if(distanceX < 0){
distanceX = distanceX * -1;
}
if(distanceY < 0){
distanceY = distanceY * -1;
}
//Add distance
distance = distanceX + distanceY;
//If current distance is shorter then the shortestdistance, to prevent it does'nt see itself as 'neighbour' and to prevent another co-ord has the same neighbour, which happens in isOk();
if(distance < shortestDistance && distanceX + distanceY != 0 && isOk(j)){
shortestDistance = distance;
locations[i][2] = j;
}
}
}
函数isOk为:
private boolean isOk(int j){
boolean result = false;
for(int i = 0; i < 20; i++){
if(locations[i][2] == j){
result = false;
}
else{
result = true;
}
}
return result;
}
那么,我想问的是我做错了什么?我仍然得到了一些项目(在20 * 10存储中),它们与最近的邻居具有相同的项目。
发布于 2013-04-26 19:49:10
您可能必须将邻居初始化为对您的isOK
方法合适的值。这样的值例如是-1。
for(int i = 0; i < 20; i++) locations[i][2] = -1;
isOk
还包含一个小错误。当发现j
是另一个位置的邻居时,应停止环路:
private boolean isOk(int j){
for(int i = 0; i < 20; i++){
if (locations[i][2] == j) return false;
}
return true;
}
https://stackoverflow.com/questions/16212311
复制相似问题