Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

axis‐aligned rectangles intersection

Tags:

algorithm

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

like image 424
SeekForaGoodJob Avatar asked Jul 24 '10 11:07

SeekForaGoodJob


People also ask

What is an axis-aligned rectangle?

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.

How do you find the intersection of a rectangle?

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 ...

How do you find the intersection of two rectangles in Java?

Rectangle rect1 = new Rectangle(100, 100, 200, 240); Rectangle rect2 = new Rectangle(120, 80, 80, 120); Rectangle intersection = rect1. intersection(rect2);

How do you know if two rotated rectangles overlap?

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.


1 Answers

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.

like image 147
Eyal Schneider Avatar answered Oct 14 '22 11:10

Eyal Schneider