All examples By author By category About

chabb

Rectangle Intersection Problem

The rectangle intesection problem tries to find all intersection between N different rectangles.

One naive approach would be to check every rectangle against every rectangle; this would take O(N^2) time for N rectangles. A better approach would be the use a sweep line; this sweep line would stop when we cross the left boundary of a rectangle, and this rectangle is added to the set of active rectangles. When we cross the right boundary of a rectangle, we remove the rectangle from the set of active rectangles.

We must then report all intersections between a newly activated rectangle that lie on the scan line, and the set of active rectangles. To do this, we just have to check if the vertical segment of the rectangle overlap. The key to a good solution is to organize the active rectangles so that intersection,deletion, and detection are executed efficiently.

I have choosed to use a Min-Priority Queue to manage the insertion and deletion. A pass thru a sorted array of x values of rectangles would work too.

I am simply testing the current segment against active segments, but a data structure like an interval tree could be used. This would yiels an execution time of O(Nlg(N)+F) where F is the number of rectangle intersections and N the number of line segments inserted in the interval tree

Notice how the sets of active rectangle evolves as the sweep line advances.