2013-04-25 67 views
0

我被困在學校項目的這一部分,我必須得到兩個座標之間的最短路線(旅行推銷員問題)。我在這裏做了一些事情來獲得最近鄰居的合作伙伴,但是一些合作伙伴擁有最近的鄰居,我不想這樣做。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的存儲空間中)與最近的鄰居有相同的物品。

+0

您的實際問題是什麼? – likeitlikeit 2013-04-25 10:56:34

+0

如何防止索引或位置具有相同的最近鄰居。或者實際上我在做什麼錯在這裏 – Ian 2013-04-25 11:22:35

+0

抱歉回覆,但你爲什麼要這麼做? – likeitlikeit 2013-04-25 11:27:43

回答

1

您可能必須將鄰居初始化爲適合您的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; 
} 
+0

我這樣做了,它已修復,謝謝!我現在必須對這個問題做些什麼嗎?現在它已經被清除了,或者我可以離開它嗎? – Ian 2013-04-26 12:21:52

+0

我想你可以離開它。但是,我從來沒有問過關於stackoverflow的問題。 :-) – david 2013-04-26 12:27:19