How to compute the union polygon of two (or more) rectangles

后端 未结 4 1629
无人及你
无人及你 2021-02-06 10:10

For example we have two rectangles and they overlap. I want to get the exact range of the union of them. What is a good way to compute this?

These are the two overlappi

4条回答
  •  闹比i
    闹比i (楼主)
    2021-02-06 10:37

    There exists a Line Sweep Algorithm to calculate area of union of n rectangles. Refer the link for details of the algorithm.

    As said in article, there exist a boolean array implementation in O(N^2) time. Using the right data structure (balanced binary search tree), it can be reduced to O(NlogN) time.

    Above algorithm can be extended to determine vertices as well.

    Details:

    Modify the event handling as follows:

    When you add/remove the edge to the active set, note the starting point and ending point of the edge. If any point lies inside the already existing active set, then it doesn't constitute a vertex, otherwise it does.

    This way you are able to find all the vertices of resultant polygon.


    Note that above method can be extended to general polygon but it is more involved.

提交回复
热议问题