我在这个问题上遇到了一个问题。
背景是我们需要让用户输入农场中的石头数量,然后他们将输入石头的坐标。输入坐标后,我们需要检查它们是否可以形成矩形。
下面是示例输入和输出:
9(岩石数量)坐标:输出为22 22 54 24 49 29 49 610 410 6
但是,我不知道如何找出矩形。我在比较那里的坐标时遇到了一些问题,你们能帮我吗?
从此链接检查这个聪明的解决方案
find the center of mass of corner points: cx=(x1+x2+x3+x4)/4, cy=(y1+y2+y3+y4)/4
test if square of distances from center of mass to all 4 corners are equal
bool isRectangle(double x1, double y1,
double x2, double y2,
double x3, double y3,
double x4, double y4)
{
double cx,cy;
double dd1,dd2,dd3,dd4;
cx=(x1+x2+x3+x4)/4;
cy=(y1+y2+y3+y4)/4;
dd1=sqr(cx-x1)+sqr(cy-y1);
dd2=sqr(cx-x2)+sqr(cy-y2);
dd3=sqr(cx-x3)+sqr(cy-y3);
dd4=sqr(cx-x4)+sqr(cy-y4);
return dd1==dd2 && dd1==dd3 && dd1==dd4;
}
约束 1:两个对角线的中心应该相同。约束 2:从一个顶点开始的两条线的点积应为零。
bool isRectangle(double x1, double y1,
double x2, double y2,
double x3, double y3,
double x4, double y4)
{
bool bCenterEqual = ((x1+x3)==(x2+x4) && (y1+y3)==(y2+y4));
if(!bCenterEqual)
return false;
if((x2-x1)*(x4-x1)+(y2-y1)*(y4-y1)!=0)
return false;
return true;
}