我实现了n个点的四叉树结构,以及在给定矩形内返回点数组的方法。我似乎找不到一个算法来有效地找到离另一个给定点最近的点。我漏掉了什么明显的东西吗?我认为递归解决方案是正确的方法吗?
我在目标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;
}
更近但没有雪茄!
发布于 2013-12-30 17:16:37
找到最小的正方形,你的搜索点在中心,而在那个矩形内正好还有一个点(你需要做的搜索数量)。
设x是到另一点的距离。
然后找出正方形内的所有点,它的边是2x,中心围绕着你的第一点。对于这个正方形中的每个点,计算出从搜索点到搜索点的距离,并找到最近的点。
更新:如何找到一个以搜索点为中心的正方形,其中正好包含另一个点?
找个随机点。设到那个随机点的距离是x,找到所有大小为x的点,以搜索点为中心。如果该方格中有非零点数,则随机选择一个点并重复。如果没有点,将搜索平方大小增加到(2-0.5)*x (在下一步(2-0.25)*x等等)。
https://stackoverflow.com/questions/20837530
复制相似问题