首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >JAVA -检查值是否不在其他索引2D数组中

JAVA -检查值是否不在其他索引2D数组中
EN

Stack Overflow用户
提问于 2013-04-25 18:26:56
回答 1查看 612关注 0票数 0

我被困在学校项目的这一部分,我必须得到两个坐标之间的最短路线(旅行推销员问题)。我在这里做了一点东西来获得最近邻居的共同利益,但有几个共同利益集团有相同的最近邻居,我不想要这样的情况。

我想出了一些方法来解决这个问题,但它不起作用,而且我也不知道为什么。

distance是当前位置与其他位置之间的当前距离。我认为shortestDistance在某种程度上是不言而喻的。

locations[20][3]是一个2D数组,我在其中存储了Xco-ord、Yco-ord和每个co-ord的最近邻居。x在x中,Y在x中,邻居在x中

代码语言:javascript
运行
复制
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为:

代码语言:javascript
运行
复制
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存储中),它们与最近的邻居具有相同的项目。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-04-26 19:49:10

您可能必须将邻居初始化为对您的isOK方法合适的值。这样的值例如是-1。

代码语言:javascript
运行
复制
for(int i = 0; i < 20; i++) locations[i][2] = -1;

isOk还包含一个小错误。当发现j是另一个位置的邻居时,应停止环路:

代码语言:javascript
运行
复制
private boolean isOk(int j){
    for(int i = 0; i < 20; i++){
        if (locations[i][2] == j) return false;
    }
    return true;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16212311

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档