使用Quadtree 等空间数据结构来存储您的点。四叉树中的每个节点都有一个边界框和一组 4 个子节点,以及一个点列表(叶节点除外)。这些点存储在叶子节点中。
点四叉树是对用于表示二维点数据的二叉树的改编。它共享所有四叉树的特征,但它是一棵真正的树,因为细分的中心总是在一个点上。树的形状取决于处理数据的顺序。它通常在比较二维有序数据点时非常有效,通常在 O(log n) 时间内运行。
对于每个点,维护一组独立于该点的所有点。
将所有点插入四叉树,然后遍历这些点并使用四叉树找到独立于每个点的点:
main()
{
for each point p
insert p into quadtree
set p's set to empty
for each point p
findIndependentPoints(p, root node of quadtree)
}
findIndependentPoints(Point p, QuadTreeNode n)
{
Point f = farthest corner of bounding box of n
if distance between f and p < 1
return // none of the points in this node or
// its children are independent of p
for each point q in n
if distance between p and q > 1
find intersection r of q's set and p's set
if r is non-empty then
p, q, r are the 3 points -> ***SOLVED***
add p to q's set of independent points
add q to p's set of independent points
for each subnode m of n (up 4 of them)
findIndependentPoints(p, m)
}
你可以加快速度:
find intersection r of q's set and p's set
通过将每个集合存储为四叉树。然后你可以通过在 q 的四叉树中搜索一个独立于 p 的点来找到交集,方法是使用相同的 early-out 技术:
// find intersection r of q's set and p's set:
// r = findMututallyIndependentPoint(p, q's quadtree root)
Point findMututallyIndependentPoint(Point p, QuadTreeNode n)
{
Point f = farthest corner of bounding box of n
if distance between f and p < 1
return // none of the points in this node or
// its children are independent of p
for each point r in n
if distance between p and r > 1
return r
for each subnode m of n (up 4 of them)
findMututallyIndependentPoint(p, m)
}
使用四叉树的替代方法是使用K-d trees,它可以生成更平衡的树,其中每个叶节点距根的深度相似。在这种情况下,寻找独立点的算法是相同的,只是数据结构中的每个节点最多只能有 2 个而不是 4 个子节点,并且每个级别的边界框的大小都是可变的。