Fast algorithm to find the x closest points to a given point on a plane

限于喜欢 提交于 2019-11-28 07:02:26

What you need is a data structure appropriate for organizing points in a plane. The K-D-Tree is often used in such situations. See k-d tree on Wikipedia.

Here, I found a general description of Geometric Algorithms


UPDATE

I ported a Java implementation of a KD-tree to C#. Please see User:Ojd/KD-Tree on RoboWiki. You can download the code there or you can download CySoft.Collections.zip directly from my homepage (only download, no docu).

For a given point (not all of them) and as the number of points is not extreme, you could calculate the distance from each point:

var points = new List<Point>();
Point source = ...
....
var closestPoints = points.Where(point => point != source).
                           OrderBy(point => NotReallyDistanceButShouldDo(source, point)).
                           Take(20);

private double NotReallyDistanceButShouldDo(Point source, Point target)
{
   return Math.Pow(target.X - source.X, 2) + Math.Pow(target.Y - source.Y, 2);
}

(I've used x = 20)

The calculation are based on doubles so the fpu should be able to do a decent job here. Note that you might get better performance if Point is a class rather than a struct.

You need to create a distance function, then calculate distance for every point and sort the results, and take the first x.

If the results must be 100% accurate then you can use the standard distance function:

d = SQRT((x2 - x1)^2 + (y2 - y1)^2)

To make this more efficent. lets say the distance is k. Take all points with x coordinates between x-k and x+k. similarly take, y-k and y+k. So you have removed all excess coordinates. now make distance by (x-x1)^2 + (y-y1)^2. Make a min heap of k elements on them , and add them to the heap if new point < min(heap). You now have the k minimum elements in the heap.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!