java—最近的一对点,递归没有在正确的区域停止

vof42yt1  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(206)

正在研究最近点算法。我正在用一个二维数组 int 他进来了。不知为什么我没有得到正确的答案。我在中的递归有什么问题 conquer ? 我想这就是问题所在。

package ClosestPair;

import java.awt.Point;
import java.util.Arrays;

public class ClosestPair{   

public double divide(int[][] data){

    int size = data.length;

    int[][] X_L = new int[size/2][2];
    int[][] X_R = new int[size/2][2];
    int[][] Y_L = new int[size/2][2];
    int[][] Y_R = new int[size/2][2];
    int[][] P_L = new int[size][2];
    int[][] P_R = new int[size][2];

    ////////// X Portion ////////////////////////////
    //sort the points
    int[][] temp = data;
    Arrays.sort(temp, new ColumnComparator(0));

    //split the points
    for (int i = 0; i < temp.length/2; i++){
        X_L[i][0] = temp[i][0];
        X_L[i][1] = temp[i+1][1];
        X_R[i][0] = temp[i+temp.length/2][0];
        X_R[i][1] = temp[i+temp.length/2][1];
    }

    ////////// Y Portion ////////////////////////////
    Arrays.sort(temp, new ColumnComparator(1));
            //split the points
            for (int i = 0; i < temp.length/2; i++){
                Y_L[i][0] = temp[i][0];
                Y_L[i][1] = temp[i+1][1];
                Y_R[i][0] = temp[i+temp.length/2][0];
                Y_R[i][1] = temp[i+temp.length/2][1];
            }

            //P_L
            P_L= appendArrays(X_L, Y_L);

            //P_R
            P_R= appendArrays(X_R, Y_R);

            if(conquer(P_L)< conquer(P_R)) return conquer(P_L);

            return conquer(P_R);        
}

public double conquer(int[][] array){
    if(array.length == 2){
        return distance(array);
    }

    int[][] temp1 = new int[array.length/2][2];
    int[][] temp2 = new int[array.length/2][2];
    int length = array.length/4;
    for (int i = 0; i < length; i++){
        temp1[i][0] = array[i][0];
        temp1[i][1] = array[i+1][1];
        temp2[i][0] = array[i+array.length/2][0];
        temp2[i][1] = array[i+array.length/2][1];
    }       
    return conquer(temp1);
}

 private static int[][] appendArrays(int[][] array1, int[][] array2) {
        int[][] ret = new int[array1.length + array2.length][];
        int i = 0;
        for (;i<array1.length;i++) {
            ret[i] = array1[i];
        }
        for (int j = 0;j<array2.length;j++) {
            ret[i++] = array2[j];
        }
        return ret;
    }

public double distance(int[][] points){
    //pair distance
    int a = (points[0][0]+points[1][0]);
    int b = (points[1][1]+points[1][1]);
    return Math.sqrt(  Math.pow(a, 2) + Math.pow(b, 2)    );
}

}
zzzyeukh

zzzyeukh1#

计算距离的公式有误。应该是的

int a = (points[0][0]-points[1][0]);
int b = (points[1][1]-points[1][1]);
return Math.sqrt(  Math.pow(a, 2) + Math.pow(b, 2)    );

也可以使用特殊功能:

int x = (points[0][0]-points[1][0]);
int y = (points[1][1]-points[1][1]);
return Math.hypot(x,y);

相关问题