Determine if two rectangles overlap each other?

前端 未结 23 1358
礼貌的吻别
礼貌的吻别 2020-11-22 04:09

I am trying to write a C++ program that takes the following inputs from the user to construct rectangles (between 2 and 5): height, width, x-pos, y-pos. All of these rectang

23条回答
  •  星月不相逢
    2020-11-22 05:11

    If the rectangles overlap then the overlap area will be greater than zero. Now let us find the overlap area:

    If they overlap then the left edge of overlap-rect will be the max(r1.x1, r2.x1) and right edge will be min(r1.x2, r2.x2). So the length of the overlap will be min(r1.x2, r2.x2) - max(r1.x1, r2.x1)

    So the area will be:

    area = (max(r1.x1, r2.x1) - min(r1.x2, r2.x2)) * (max(r1.y1, r2.y1) - min(r1.y2, r2.y2))
    

    If area = 0 then they don't overlap.

    Simple isn't it?

提交回复
热议问题