Rectangles Covering

后端 未结 12 1195

I have N rectangles with sides parallel to the x- and y-axes. There is another rectangle, model. I need to create an algorithm that can tell whether the

12条回答
  •  萌比男神i
    2020-12-14 08:24

    Here's a generic algorithm

    1. is there any rectangle covering the whole model?
      if yes you are done
    2. if no are there any rectangles partially covering the model?
      if yes
    3. is the union of all the intersections of rectangle and model equal to the model
      if 2. or 3. is no then the answer is no, otherwise it is yes

    Now the question is how to do the above efficiently. The above can be done in a single loop over all polygons, so I think you are looking at O(n) time.

    If you need to create efficient algorithm that will test multiple models, or if you must optimize for fastest answer possible (at the expense of preparing the data) then you are looking for a structure that will allow quick answer to question if a rectangle intersects (or contains) a rectangle.

    If you use, for example kd-trees, I believe that this can be answered in O(log n) time - but the important variable in this algorithm is also the number of found rectangles k. You will end up with something like O(k + log n) and you will also need to do the union part to test if the model is covered.

    My guess is that the union could be computed in O(k log k), so if k is small then you are looking at O(log n) and if k is comparable to n then it should be O(k log k).

    See also this question.

    EDIT: In response to complexity of intersections and unions.

    In more details, we have two scenarios depending on if k << n or k comparable to n

    a) in case of k << n and assuming polynomial complexity for intersection/union (so here I give up the guess O(k log k) ) we have:

    • log n to find a range in kd indexed tree (of rectangles),
    • k steps to retrieve all the rectangles in that 'branch',
    • f(k) some polynomial time to calculate intersections and union

    The total is O(k + log n + f(k)), which is directly equal to O(log n) since big O depends only on the fastest growing term.

    In this case the more significant part of the algorithm is finding the polygons.

    b) in the case of k comparable to n we must take a look at the complexity of intersection and union algorithms (notice the parallel here on how the RDBMs, depending on selectivity, might use index or do table scan; it is a similar choice to what we have here).
    If k is big enough the algorithm becomes less of an algorithm for finding rectangles that intersect with the rectangle and becomes more of an algorithm for calculating the union of polygons.

    But, i believe that the kd tree can also help in finding the intersection of segments (which are necessary to build the union), so even this part of algorithm might not need k^2 time. At this point I would investigate efficient algorithms for calculating the area of unions.

提交回复
热议问题