用于在距离另一个点一定距离的2D网格上查找所有点的算法

时间:2011-12-31 19:34:32

标签: grid 2d distance point

我在2D网格(x,y)上有一些观点,我需要找到距离该点n个距离的所有点。我测量距离的方法是使用两点之间的距离公式。有谁知道怎么做?

编辑:仅供参考,我要做的是编写一些AI路径查找,它将与使用基于网格的位置的系统中的目标保持一定距离。目前我正在使用A *路径查找,但我不确定这是否重要或有所不同,因为我对这些东西不熟悉。

5 个答案:

答案 0 :(得分:2)

这就是我要做的事情:

  1. 首先过滤掉x或y上比D更远的所有点。这些肯定在半径D的圆外。这是一个更简单的计算,它可以很快消除大量的工作。这是一个外部边界框优化。

  2. 您还可以使用内部边界框优化。如果这些点在x或y上比D * sqrt(2)/ 2更接近,那么它们肯定在半径D的圆内。这也比计算距离公式便宜。

  3. 然后你有一个较小数量的候选点可能在半径D的圆内。对于这些,使用距离公式。请记住,如果D = sqrt(Δx 2 +Δy 2 ),那么D 2 =Δx 2 +Δy 2
    因此,您可以跳过计算平方根的成本。


  4. 因此,在伪代码中,您可以执行以下操作:

    for each point
    begin
        if test 1 indicates the point is outside the outer bounding box, 
        then skip this point
    
        if test 2 indicates the point is inside the inner bounding box, 
        then keep this point
    
        if test 3 indicates the point is inside the radius of the circle, 
        then keep this point
    end
    

答案 1 :(得分:0)

此问题称为范围查询。蛮力解决方案与您所描述的一样:计算所有点距参考点的距离,并返回距离小于所需范围值的点。

强力算法是O(N ^ 2)。然而,有更高效的算法使用spatial indexes来降低算法复杂度和距离计算的数量。例如,您可以使用R-Tree索引积分。

答案 2 :(得分:0)

它被称为最近邻搜索。更多http://en.wikipedia.org/wiki/Nearest_neighbor_search

有开放的库。我使用过为C编写的一个并推荐它​​:http://www.cs.umd.edu/~mount/ANN/。 ANN代表近似最近邻,但是,您可以关闭近似值并找到确切的最近邻居。

答案 3 :(得分:0)

这不会使用距离公式,但是如果你正在寻找距离恰好很近的点,也许你可以使用sin / cos?

在伪代码中:

for degrees in range(360):
    x = cos(degrees) * n
    y = sin(degrees) * n
    print x, y

这将以360度的增量打印每个点n。

答案 4 :(得分:0)

Java实现:

public static Set<Point> findNearbyPoints(Set<Point> pts, Point centerPt, double radius) {
    Set<Point> nearbyPtsSet = new HashSet<Point>();
    double innerBound = radius * (Math.sqrt(2.0) / 2.0);
    double radiusSq = radius * radius;
    for (Point pt : pts) {
        double xDist = Math.abs(centerPt.x - pt.x);
        double yDist = Math.abs(centerPt.y - pt.y);
        if (xDist > radius || yDist > radius)
            continue;
        if (xDist > innerBound || yDist > innerBound)
            continue;
        if (distSq(centerPt, pt) < radiusSq)
            nearbyPtsSet.add(pt);
    }
    return nearbyPtsSet;
}
相关问题