Maximum possible number of rectangles that can be crossed with a single straight line

后端 未结 6 1676
执笔经年
执笔经年 2020-12-24 06:11

I found this challenge problem which states the following :

Suppose that there are n rectangles on the XY plane. Write a program to calculate the maxi

6条回答
  •  情书的邮戳
    2020-12-24 06:36

    If you consider a rotating line at angle Θ and if you project all rectangles onto this line, you obtain N line segments. The maximum number of rectangles crossed by a perpendicular to this line is easily obtained by sorting the endpoints by increasing abscissa and keeping a count of the intervals met from left to right (keep a trace of whether an endpoint is a start or an end). This is shown in green.

    Now two rectangles are intersected by all the lines at an angle comprised between the two internal tangents [example in red], so that all "event" angles to be considered (i.e. all angles for which a change of count can be observed) are these N(N-1) angles.

    Then the brute force resolution scheme is

    • for all limit angles (O(N²) of them),

      • project the rectangles on the rotating line (O(N) operations),

      • count the overlaps and keep the largest (O(N Log N) to sort, then O(N) to count).

    This takes in total O(N³Log N) operations.

    Assuming that the sorts needn't be re-done in full for every angle if we can do them incrementally, we can hope for a complexity lowered to O(N³). This needs to be checked.


    Note:

    The solutions that restrict the lines to pass through the corner of one rectangle are wrong. If you draw wedges from the four corners of a rectangle to the whole extent of another, there will remain empty space in which can lie a whole rectangle that won't be touched, even though there exists a line through the three of them.

提交回复
热议问题