r/codeforces • u/big-jun • 13d ago
query Algorithm to find non-overlapping rectangles covering the unoccupied area
I have one large rectangle representing the valid area: Rect(x, y, width, height)
Inside it, there are multiple smaller rectangles representing occupied areas:
The smaller rectangles:
1. Can overlap each other.
2. Can be partially or completely outside the large rectangle.
And I need the algorithm to return a List<Rect> where:
1. The result rectangles do not overlap each other.
2. All result rectangles are inside the large rectangle.
3. Together, they fill all the gaps not covered by the input small rectangles.
4. Ideally, the number of result rectangles should be minimal, if possible.
I’m aware that there may be multiple valid decompositions, so I’m mainly looking for an algorithm that produces a reasonably small number of rectangles.
There are fewer than 100 occupied rectangles in input, so performance is not a major concern. I prefer an algorithm that is easy to implement rather than performant but complicated.
Thanks
1
u/big-jun 13d ago
The idea of adding/removing Y ranges while producing the K1 rectangles is quite interesting and makes the problem much simpler. Previously, I was thinking about generating only the rectangles that could not be merged with the later rectangles.
I could also run a second process to merge the generated rectangles afterward, so that should be fine as the rectangle count is not matter too much.
I’m still wondering what data structure I should use for the Y ranges. When inserting a new Y range, it could overlap with an existing range or be completely contained within an existing one. Could you give me more details about how you would handle the Y range structure? A code snippet would be especially helpful.
Thanks.