从此帖here的解决方案开始。似乎使用点(1,0),( - 1,0),(0,1)和(0,-1),当它应该返回这些点确实形成正方形时,解决方案失败。
也许我的实施有问题。这是我的代码:
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
class Solution {
public:
bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) {
double x1 = p1[0], x2 = p2[0], x3 = p3[0], x4 = p4[0];
double y1 = p1[1], y2 = p2[1] , y3 = p3[1], y4 = p4[1];
double cx = (x1+x2+x3+x4)/4;
double cy = (y1+y2+y3+y4)/4;
double a1 = (cx - x1), a2 = (cy - y1);
double b1 = (cx - x2), b2 = (cy - y2);
double c1 = (cx - x3), c2 = (cy - y3);
double d1 = (cx - x4), d2 = (cy - y4);
double dd1 = a1*a1 + a2*a2;
double dd2 = b1*b1 + b2*b2;
double dd3 = c1*c1 + c2*c2;
double dd4 = d1*d1 + d2*d2;
double epsilon = 0.00001;
return abs(dd1 - dd2) < epsilon && abs(dd1 - dd3) < epsilon && abs(dd1 - dd4) < epsilon;
}
};
int main() {
vector<int> p1, p2, p3, p4;
p1.push_back(1);
p1.push_back(0);
p2.push_back(-1);
p2.push_back(0);
p3.push_back(0);
p3.push_back(1);
p4.push_back(0);
p4.push_back(-1);
Solution m;
bool x;
x = m.validSquare(p1,p2,p3,p4);
if(x == 1) {
cout << "Points form a square" << endl;
}
else {
cout << "Points do not form a square" << endl;
}
return 0;
}
链接中的解决方案肯定是正确的但由于某些原因这四点我得不到准确的回报。如果有人有任何建议,请告诉我。
更新
根据用户的建议。我换了几行。使用点(0,0),(5,0),(5,4)和(0,4)不应该返回这些点可以形成正方形。不幸的是,我的更新代码仍然返回这些点是正方形所以我不确定问题是什么。
这是我的代码:
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
class Solution {
public:
bool isFloatEqual(double a, double b) {
double epsilon = 0.001;
return abs(a - b) < epsilon;
}
bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) {
double x1 = p1[0], x2 = p2[0], x3 = p3[0], x4 = p4[0];
double y1 = p1[1], y2 = p2[1] , y3 = p3[1], y4 = p4[1];
double cx = (x1+x2+x3+x4)/4;
double cy = (y1+y2+y3+y4)/4;
double a1 = (cx - x1), a2 = (cy - y1);
double b1 = (cx - x2), b2 = (cy - y2);
double c1 = (cx - x3), c2 = (cy - y3);
double d1 = (cx - x4), d2 = (cy - y4);
double dd1 = a1*a1 + a2*a2;
double dd2 = b1*b1 + b2*b2;
double dd3 = c1*c1 + c2*c2;
double dd4 = d1*d1 + d2*d2;
return isFloatEqual(dd1,dd2) && isFloatEqual(dd1, dd3) &&isFloatEqual(dd1, dd4);
}
};
int main() {
vector<int> p1, p2, p3, p4;
p1.push_back(0);
p1.push_back(0);
p2.push_back(5);
p2.push_back(0);
p3.push_back(5);
p3.push_back(4);
p4.push_back(0);
p4.push_back(4);
Solution m;
bool x;
x = m.validSquare(p1,p2,p3,p4);
if(x == 1) {
cout << "Points form a square" << endl;
}
else {
cout << "Points do not form a square" << endl;
}
return 0;
}
答案 0 :(得分:1)
你有y3 = p3[2]
- 应该是y3 = p3[1]
吗?这很容易在c#,BTW中找到;)