Reputation: 633
Good afternoon.
My situation:
Questions:
Thanks :-).
Upvotes: 13
Views: 6799
Reputation: 80187
It seems that your set of rectangles may be dynamic ("...for adding rectangles..."). In this case - 2D Interval tree could be the solution.
Upvotes: 3
Reputation: 6169
R-Tree is the best data structure suitable for this use case. R-trees are tree data structures used for spatial access methods, i.e., for indexing multi-dimensional information such as geographical coordinates, rectangles or polygons. The information of all rectangles can be stored in tree form so searching will be easy
Wikipedia page, short ppt and the research paper will help you understand the concept.
Upvotes: 22
Reputation: 86506
A rectangle (left, top, right, bottom)
contains a point (x, y)
if left < x < right
and top < y < bottom
(assuming coordinates increase going downwards, which is the case with most hardware i've seen; if your coordinates increase going upwards, the more traditionally mathematical case, swap top
and bottom
). You're not going to get much more efficient than that for the test.
If you consider a rectangle as "containing" a point if it's on the border as well, then replace all the <
s with <=
.
As for what to do with the collection of rectangles...i dunno. I'd think a list sorted by the coordinates of the corners would do something, but i'm not really seeing much benefit to it...at most, you'd be cutting your list of stuff to check by half, on average (with the worst case still requiring checking everything). Half of a whole freaking lot can still be a whole lot. :)
Upvotes: 2
Reputation: 472
Here is a simple solution.
Upvotes: 2
Reputation: 35011
In java you can use shape.contains
But in general, assuming a rectangle is defined by (x,y,width,height) you do
if (pt.x >= x && pt.x <= x + width && pt.y >= y && pt.y <= y + height) ...
If you have all your rectangles in a collection you can iterate over the collection and find the ones that contain the point
Upvotes: 3