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

后端 未结 6 1647
执笔经年
执笔经年 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:38

    How about the following algorithm:

    RES = 0 // maximum number of intersections
    CORNERS[] // all rectangles corners listed as (x, y) points
    
    for A in CORNERS
        for B in CORNERS // optimization: starting from corner next to A
            RES = max(RES, CountIntersectionsWithLine(A.x, A.y, B.x, B.y))
    
    return RES
    

    In other words, start drawing lines from each rectangle corner to each other rectangle corner and find the maximum number of intersections. As suggested by @weston, we can avoid calculating same line twice by starting inner loop from the corner next to A.

提交回复
热议问题