My situation
- Input: a set of rectangles
- each rect is comprised of 4 doubles like this: (x0,y0,x1,y1)
- they are not ‘rotated’ at any angle, all they are ‘normal’ rectangles that go ‘up/down’ and ‘left/right’ with respect to the screen
- they are randomly placed – they may be touching at the edges, overlapping , or not have any contact
- I will have several hundred rectangles
- this is implemented in C#
I need to find
- The area that is formed by their overlap – all the area in the canvas that more than one rectangle ‘covers’ (for example with two rectangles, it would be the intersection)
- I don’t need the geometry of the overlap – just the area (example: 4 sq inches)
- Overlaps shouldn’t be counted multiple times – so for example imagine 3 rects that have the same size and position – they are right on top of each other – this area should be counted once (not three times)
Example
- The image below contains thre rectangles: A,B,C
- A and B overlap (as indicated by dashes)
- B and C overlap (as indicated by dashes)
- What I am looking for is the area where the dashes are shown
–
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAA--------------BBB AAAAAAAAAAAAAAAA--------------BBB AAAAAAAAAAAAAAAA--------------BBB AAAAAAAAAAAAAAAA--------------BBB BBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBBBB BBBBBB-----------CCCCCCCC BBBBBB-----------CCCCCCCC BBBBBB-----------CCCCCCCC CCCCCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCCCCC
An efficient way of computing this area is to use a sweep algorithm. Let us assume that we sweep a vertical line L(x) through the union of rectangles U:
We still have to solve the 1D problem. You want a 1D structure, which computes dynamically a union of (vertical) segments. By dynamically, I mean that you sometimes add a new segment, and sometimes remove one.
I already detailed in my answer to this collapsing ranges question how to do it in a static way (which is in fact a 1D sweep). So if you want something simple, you can directly apply that (by recomputing the union for each event). If you want something more efficient, you just need to adapt it a bit:
This is your dynamic algorithm. Assuming that you will use sorted sets with log-time location queries to represent D1…Dk, this is probably the most efficient non-specialized method you can get.