Intersection of N rectangles

前端 未结 6 521
野趣味
野趣味 2020-12-25 15:18

I\'m looking for an algorithm to solve this problem:

Given N rectangles on the Cartesian coordinate, find out if the intersection of those rectangles is empty or no

6条回答
  •  执笔经年
    2020-12-25 15:50

    Since the rectangles must not be parallel to the axis, it is easier to transform the problem to an already solved one: compute the intersections of the borders of the rectangles.

    • build a set S which contains all borders, together with the rectangle they're belonging to; you get a set of tuples of the form ((x_start,y_start), (x_end,y_end), r_n), where r_n is of course the ID of the corresponding rectangle
    • now use a sweep line algorithm to find the intersections of those lines

    The sweep line stops at every x-coordinate in S, i.e. all start values and all end values. For every new start coordinate, put the corresponding line in a temporary set I. For each new end-coordinate, remove the corresponding line from I.

    Additionally to adding new lines to I, you can check for each new line whether it intersects with one of the lines currently in I. If they do, the corresponding rectangles do, too.

    You can find a detailed explanation of this algorithm here.

    The runtime is O(n*log(n) + c*log(n)), where c is the number of intersection points of the lines in I.

提交回复
热议问题