我被困在學校項目的這一部分,我必須得到兩個座標之間的最短路線(旅行推銷員問題)。我在這裏做了一些事情來獲得最近鄰居的合作伙伴,但是一些合作伙伴擁有最近的鄰居,我不想這樣做。JAVA-檢查值是否不在其他索引的二維數組
我想到了一些能夠解決這個問題的方法,但它並不奏效,而且我弄不明白爲什麼。
distance
是當前位置與其他位置之間的當前距離。 shortestDistance
那種說話本身就是我想的。
locations[20][3]
是一個2D數組,其中我存儲了每個協作的Xco-ord,Yco-ord和最近的鄰居。 X是在[X] [0],Y在[X] [1]和鄰居[X] [2]
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的存儲空間中)與最近的鄰居有相同的物品。
您的實際問題是什麼? – likeitlikeit 2013-04-25 10:56:34
如何防止索引或位置具有相同的最近鄰居。或者實際上我在做什麼錯在這裏 – Ian 2013-04-25 11:22:35
抱歉回覆,但你爲什麼要這麼做? – likeitlikeit 2013-04-25 11:27:43