Count number of points inside a circle fast

前端 未结 6 1869
长发绾君心
长发绾君心 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-24 00:13

    Build a spatial subdivision structure such as a quadtree or KD-tree of the points. At each node store the amount of points covered by that node. Then when you need to count the points covered by the lookup circle, traverse the tree and for each subdivision in a node check if it is fully outside the circle, then ignore it, if it is fully inside the circle then add its count to the total if it intersects with the circle, recurse, when you get to the leaf, check the point(s) inside the leaf for containment.

    This is still O(n) worst case (for instance if all the points lie on the circle perimeter) but average case is O(log(n)).

提交回复
热议问题