KdTree最近邻搜索算法无法正常工作

时间:2014-03-07 00:24:10

标签: java algorithm nearest-neighbor kdtree

我正在java中实现KdTree。我完成了大部分程序的其余部分,但我似乎无法让我的最近邻搜索算法正常​​工作。它总是返回根节点的值,无论如何。这是我的代码:

public Point2D nearest(Point2D p) {

    if (root == null) //if there are no nodes in the tree
        return null;
    else
        return nearest(p, root, root.point);            

}
  • rect 是一个RectHV对象,对应于节点的边界。

    public Point2D nearest(Point2D p, Node n, Point2D nearest) {
    
    if (n == null) {
        return nearest;
    }
    
    if (p.distanceSquaredTo(nearest) > p.distanceSquaredTo(n.point)) {
        nearest = n.point;
    }
    if (n.xAxis) { //the xaxis value is a boolean, if it is true,
                   //the node splits on the x axis, false it splits on y
    
        if (p.x() < n.point.x() && p.distanceSquaredTo(nearest) < n.rect.distanceTo(p)) {
            nearest = nearest(p, n.leftnode, nearest);
            System.out.println("look left 1");
        } else {
            nearest = nearest(p, n.rightnode, nearest);
            System.out.println("look right 1");
        }
    } else {
        if (p.y() < n.point.y() && p.distanceSquaredTo(nearest) < n.rect.distanceTo(p)) {
            nearest = nearest(p, n.leftnode, nearest);
            System.out.println("look left 2");
        } else {
            nearest = nearest(p, n.rightnode, nearest);
            System.out.println("look right 2");
        }
    }
    return nearest;
    

    }

我认为我的算法太简单了。我的理由是,如果查询点和候选点的矩形之间的distanceSquared大于已经建立的最近点,则不要搜索该树。

1 个答案:

答案 0 :(得分:0)

问题是(1)从查询点到定义子树的点的距离不是到该子树中所有点的距离的下限,(2)最近点可能位于“其他”中“孩子。

要获得下限,可以在下降时跟踪子树中点的边界框,并使用查询点到框的距离。更简单地说,您可以使用从最近分割定义的点到半平面的距离。你需要探索两个孩子(除非修剪)。

相关问题