我已经为n个点实现了一个四叉树结构,以及一个在给定矩形内返回一个点数组的方法。我似乎无法找到一种算法来有效地找到最接近另一个给定点的点。我错过了一些明显的东西吗我假设递归解决方案是正确的方法吗?
我在Objective C工作,但伪代码没问题。另外,我实际上存储了lat,长数据,并且点之间的距离沿着一个大圆圈。
修改 这是我的树插入和细分代码
- (BOOL)insert:(id<PASQuadTreeDataPoint>)dataPoint {
BOOL pointAdded = false;
// If the point lies within the region
if(CGRectContainsPoint(self.region, dataPoint.point)) {
// If there are less than 4 points then add this point
if(self.dataPoints.count < kMaxPointsPerNode) {
[self.dataPoints addObject:dataPoint];
pointAdded = true;
}
else {
// Subdivide into 4 quadrants if not already subdivided
if(northEast == nil) [self subdivide];
// Attempt to add the point to one of the 4 subdivided quadrants
if([northEast insert:dataPoint]) return true;
if([southEast insert:dataPoint]) return true;
if([southWest insert:dataPoint]) return true;
if([northWest insert:dataPoint]) return true;
}
}
return pointAdded;
}
- (void)subdivide {
// Compute the half width and the origin
CGFloat width = self.region.size.width * 0.5f;
CGFloat height = self.region.size.height * 0.5f;
CGFloat x = self.region.origin.x;
CGFloat y = self.region.origin.y;
// Create a new child quadtree with the region divided into quarters
self.northEast = [PASQuadTree quadTreeWithRegion:CGRectMake(x + width, y, width, height)];
self.southEast = [PASQuadTree quadTreeWithRegion:CGRectMake(x + width, y + height, width, height)];
self.southWest = [PASQuadTree quadTreeWithRegion:CGRectMake(x, y + height, width, height)];
self.northWest = [PASQuadTree quadTreeWithRegion:CGRectMake(x, y, width, height)];
}
修改 编写此代码以查找包含该点的最小节点(叶):
-(PASQuadTree *)nodeThatWouldContainPoint:(CGPoint)point {
PASQuadTree *node = nil;
// If the point is within the region
if (CGRectContainsPoint(self.region, point)) {
// Set the node to this node
node = self;
// If the node has children
if (self.northEast != nil) {
// Recursively check each child to see if it would contain the point
PASQuadTree *childNode = [self.northEast nodeThatWouldContainPoint:point];
if (!childNode) childNode = [self.southEast nodeThatWouldContainPoint:point];
if (!childNode) childNode = [self.southWest nodeThatWouldContainPoint:point];
if (!childNode) childNode = [self.northWest nodeThatWouldContainPoint:point];
if (childNode) node = childNode;
}
}
return node;
}
更近但没有雪茄!
答案 0 :(得分:4)
找到最小的正方形,搜索点位于中心,正好在该矩形内的另一个点(您需要记录搜索次数)。
设x是到另一个点的距离。
然后找到一个方形中的所有点,其边长为2x并以第一个点为中心。对于此正方形内的每个点,计算距搜索点的距离并找到最接近的点。
更新:如何找到一个以搜索点为中心的方格,其中只包含另一个点?
找一个随机点。让到该随机点的距离为x。找到以搜索点为中心的x大小的正方形内的所有点。如果此正方形内有非零点数,则随机选择一个点并重复。如果没有分数,请将搜索方块大小增加到(2-0.5)* x(下一步(2-0.25)* x,依此类推。