1. 程式人生 > >如何判斷兩個矩形是否有重疊部分?(某公司校園招聘筆試試題)

如何判斷兩個矩形是否有重疊部分?(某公司校園招聘筆試試題)

#include<iostream>
#include<cmath>
using namespace std;

typedef struct rectangle
{
float centerX;
float centerY;
float width;
float height;
}Rectangle;

bool areTwoRectsOverlapped(Rectangle rect1, Rectangle rect2)
{
float verticalDistance;    //垂直距離
float horizontalDistance;  //水平距離
verticalDistance = fabs(rect1.centerX - rect2.centerX);
horizontalDistance = fabs(rect1.centerY - rect2.centerY);

float verticalThreshold;   //兩矩形分離的垂直臨界值
float horizontalThreshold; //兩矩形分離的水平臨界值
verticalThreshold = (rect1.height + rect2.height)/2;
horizontalThreshold = (rect1.width + rect2.height)/2;

if(verticalDistance > verticalThreshold || horizontalDistance > horizontalThreshold)
return false;

return true;
}


假設是確保有效的 RECT,不是無效的

RECT r1, r2;
...
RECT rCommon;
rCommon.left = max(r1.left, r2.left);
rCommon.top = max(r1.top, r2.top);
rCommon.right = min(r1.right, r2.right);
rCommon.bottom = min(r1.bottom, r2.bottom);
這個 rCommon 是這兩個矩形的交集,判斷交集部分是否是有效的矩形就可以了
int main()
{
Rectangle rect1 = {0.0, 0.0, 20.0, 10};
Rectangle rect2 = {6.0, 6.0, 2.1, 1.9};

if(areTwoRectsOverlapped(rect1, rect2))
cout << "overlapped" << endl;
else
   cout << "not overlapped" << endl;

return 0;
}