I need an algorithm that takes an unsorted array of axis aligned rectangles and returns any pair of rectangles that overlaps
Each rectangle has two variables, coordinates of the upper-left corner and the bottom-right corner
Axis-aligned means that all the rectangle sides are either parallel or perpendicular to the x- and y-axis. You can assume that each rectangle object has two variables in it: the x-y coordinates of the upper-left corner and the bottom-right corner.
The coordinates for some intersection will just be the point where "edge a" of "rectangle 1" intersects "edge x" of "rectangle 2." That is, the intersection point will have the x value of (edge a or x), and the y value of the other edge (since these rectangles are parallel to the axis the x or y value of an edge will ...
Rectangle rect1 = new Rectangle(100, 100, 200, 240); Rectangle rect2 = new Rectangle(120, 80, 80, 120); Rectangle intersection = rect1. intersection(rect2);
For each edge in both polygons, check if it can be used as a separating line. If so, you are done: No intersection. If no separation line was found, you have an intersection.
Here is a brief description of the intersection algorithm presented in DuduAlul's link.
The solution requires the usage of a search tree capable of performing range queries. A range query asks for all items with values between K1 and K2, and it should be an O(R+log N) operation, where N is the total number of tree items, and R is the number of results.
The algorithm uses the sweep approach:
1) Sort all left and right rectangle edges, according to their X value, into list L.
2) Create a new empty range search tree T, for Y ordering of rectangle tops/bottoms
3) Create a new empty result set RS of unique rectangle pairs
4) Traverse L in ascending order. For all V in L:
If V.isRightEdge()
T.remove(V.rectangle.top)
T.remove(V.rectangle.bottom)
else
For all U in T.getRange(V.rectangle.top, V.rectangle.bottom)
RS.add(<V.rectangle, U.rectangle>)
T.add(V.rectangle.top)
T.add(V.rectangle.bottom)
5) return RS
The time complexity is O(R + N log N) where R is the actual number of intersections.
-- EDIT --
I just figured out that the solution is not fully correct - the intersection test in tree T misses some cases. The tree should maintain Y intervals rather than Y values, and it should ideally be an Interval Tree.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With