Count number of points inside a circle fast

前端 未结 6 1877
长发绾君心
长发绾君心 2020-12-23 23:35

Given a set of n points on plane, I want to preprocess these points somehow faster than O(n^2) (O(nlog(n)) preferably), and then be able to answer on queries of the followi

6条回答
  •  死守一世寂寞
    2020-12-23 23:59

    Assuming you have a set of points S in a cartesian plane with coordinates (xi,yi), given an arbitrary circle with center (xc,yc) and radius r you want to find all the points contained within that circle.

    I will also assume that the points and the circle may move so certain static structures that can speed this up won't necessarily be appropriate.

    Three things spring to mind that can speed this up:

    Firstly, you can check:

    (xi-xc)^2 + (yi-yc)^2 <= r^2
    

    instead of

    sqrt((xi-xc)^2 + (yi-yc)^2) <= r
    

    Secondly, you can cull the list of points somewhat by remembering that a point can only be within the circle if:

    • xi is in the range [xc-r,xc+r]; and
    • yi is in the range [yc-r,yc+r]; and

    This is known as a bounding box. You can use it as either an approximation or to cut down your list of points to a smaller subset to check accurately with the first equation.

    Lastly, sort your points in either x or y order and then you can do a bisection search to find the set of points that are possibly within your bounding box, further cutting down on unnecessary checks.

提交回复
热议问题