在KD树中搜索速度慢

3

我正在实现一个KD树来将地图上的点聚类成组。我一直在使用维基百科的KD树文章作为参考。搜索返回了正确的最近邻点,但速度比我预期的要慢。以下是我的代码:

- (FDRKDTree *)nnSearchForPoint:(id <MKAnnotation>)point best:(FDRKDTree *)best {
// consider the current node
distToPoint = [self distanceBetweenAnnotations:self.location and:point];
if (distToPoint < best.distToPoint) {
    best = self;
}
// search near branch
int axis = depth % 2;
FDRKDTree *child = nil;
if (axis) {
    if (point.coordinate.latitude > location.coordinate.latitude)
        child = rightChild;
    else
        child = leftChild;
} else {
    if (point.coordinate.longitude > location.coordinate.longitude)
        child = rightChild;
    else
        child = leftChild;
}
if (child != nil)
    best = [child nnSearchForPoint:point best:best];

child = nil;
//search the away branch - maybe
if (axis) {
    if (fabs(point.coordinate.latitude - self.location.coordinate.latitude) <
        best.distToPoint) {
        if (point.coordinate.latitude > location.coordinate.latitude)
            child = leftChild;
        else
            child = rightChild;
    }
} else {
    if (fabs(point.coordinate.longitude - self.location.coordinate.longitude) <
        best.distToPoint) {
        if (point.coordinate.longitude > location.coordinate.longitude)
            child = leftChild;
        else
            child = rightChild;
    } 
}


if (child != nil) {
    best = [child nnSearchForPoint:point best:best];
}

return best;
}

我的问题是,我对“简单比较以查看搜索点和当前节点的分裂坐标之间的差异是否小于从搜索点到当前最佳点的距离(总体坐标)”的解释是否正确。我的理解是:

if (fabs(point.coordinate.latitude - self.location.coordinate.latitude) < best.distToPoint)

if (fabs(point.coordinate.longitude - self.location.coordinate.longitude) < best.distToPoint)

分别表示。欢迎提出任何其他建议。

谢谢。

1个回答

0

你所做的看起来很不错,假设你的distToPointsqrt((x1-x0)**2+(y1-y0)**2)。我在Python中实现了这个算法,可以帮助交叉检查你的版本并澄清一些维基百科文章中的问题: https://gist.github.com/863301


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接