Search code examples
algorithmcomputational-geometrymathematical-optimizationrectanglesgraphics

Merging and splitting overlapping rectangles to produce non-overlapping ones


I am looking for an algorithm as follows:

Given a set of possibly overlapping rectangles (All of which are "not rotated", can be uniformly represented as (left,top,right,bottom) tuplets, etc...), it returns a minimal set of (non-rotated) non-overlapping rectangles, that occupy the same area.

It seems simple enough at first glance, but prooves to be tricky (at least to be done efficiently).

Are there some known methods for this/ideas/pointers?

Methods for not necessarily minimal, but heuristicly small, sets, are interesting as well, so are methods that produce any valid output set at all.


Solution

  • Something based on a line-sweep algorithm would work, I think:

    • Sort all of your rectangles' min and max x coordinates into an array, as "start-rectangle" and "end-rectangle" events
    • Step through the array, adding each new rectangle encountered (start-event) into a current set
    • Simultaneously, maintain a set of "non-overlapping rectangles" that will be your output set
    • Any time you encounter a new rectangle you can check whether it's completely contained already in the current / output set (simple comparisons of y-coordinates will suffice)
    • If it isn't, add a new rectangle to your output set, with y-coordinates set to the part of the new rectangle that isn't already covered.
    • Any time you hit a rectangle end-event, stop any rectangles in your output set that aren't covering anything anymore.

    I'm not completely sure this covers everything, but I think with some tweaking it should get the job done. Or at least give you some ideas... :)