JAVA - 检查值是否不在其他索引二维数组中

标签 java arrays 2d

我陷入了学校项目的这一部分,我必须获得两个坐标之间的最短路线(旅行推销员问题)。我在这里做了一些事情来获取最近邻居的坐标,但是一些坐标具有相同的最近邻居,我不希望这样。

我想了一些办法来解决这个问题,但它不起作用,我也不明白为什么。

distance 是当前位置与其他位置之间的当前距离。我认为 shortestDistance 本身就说明了问题。

locations[20][3] 是一个二维数组,我在其中存储 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 存储中)。

最佳答案

您可能必须将邻居初始化为适合您的 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;
}

关于JAVA - 检查值是否不在其他索引二维数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16212311/

相关文章:

java - Spark 流式传输和模拟 hdfs

java - Neo4j - 关系扩展器已弃用,使用最低共同祖先

java - 带有 Projection 的 Spring JPA native 查询给出 "ConverterNotFoundException"

java - 如果多个类具有相同的序列 UID,到底会发生什么情况?

c++ - 在 CGAL 中查找两个二维三角形的交集/差集的三角剖分结果

c# - XNA 中的无限滚动背景

xna - 如何在 SpriteBatch Draw XNA (2D) 中将两个 Sprite 相乘

java - 在 Java 中映射两个字符串数组

javascript - 使用 forEach() 返回数组值

arrays - Swift Loops 控制台的顺序不正确