一些计算几何的只是点
判断四个点是否是矩形:对角线交点到四个点距离是否相等
private boolean check(int[][] points, int a, int b, int c, int d) {
double x = (points[a][0] + points[b][0] + points[c][0] + points[d][0]) / 4.0;
double y = (points[a][1] + points[b][1] + points[c][1] + points[d][1]) / 4.0;
double dis1 = distance(points[a][0], points[a][1], x, y);
double dis2 = distance(points[b][0], points[b][1], x, y);
double dis3 = distance(points[c][0], points[c][1], x, y);
double dis4 = distance(points[d][0], points[d][1], x, y);
return dis1 == dis2 && dis2 == dis3 && dis3 == dis4;
}
private double distance(double a, double b, double c, double d) {
return (c - a) * (c - a) + (d - b) * (d - b);
}
三角形面积:向量积
A(x1, y1) B(x2, y2) C(x3, y3)
AB= (x2 - x1, y2 - y1)
AC= (x3 - x1, y3 - y1)
AB×AC = (x2 - x1)*(y3 - y1) - (y2 - y1)*(x3 - x1)
private double calArea(int[][] points, int a, int b, int c) {
int[] p1 = new int[]{points[b][0] - points[a][0], points[b][1] - points[a][1]};
int[] p2 = new int[]{points[c][0] - points[a][0], points[c][1] - points[a][1]};
return Math.abs(p1[0] * p2[1] - p1[1] * p2[0]) / 2.0;
}
是否正交(垂直):点积为0
贴个代码:O(N^3)
class Solution {
public:
string getKey(int a, int b) {
return to_string(a) + "_" + to_string(b);
}
double minAreaFreeRect(vector<vector<int>>& points) {
unordered_set<string> us;
for (auto &p: points) {
us.insert(getKey(p[0], p[1]));
}
double ans = 0;
for (int i = 0; i < points.size(); ++i) {
for (int j = 0; j < points.size(); ++j) {
for (int k = j + 1; k < points.size(); ++k) {
if (i == j || i == k) continue;
int x1 = points[i][0], y1 = points[i][1];
int x2 = points[j][0], y2 = points[j][1];
int x3 = points[k][0], y3 = points[k][1];
//向量点积,是否垂直
if ((x2 - x1) * (x3 - x1) + (y2 - y1) * (y3 - y1) != 0) continue;
//求另外一个点的坐标
int x4 = x2 + x3 - x1, y4 = y2 + y3 - y1;
if (us.count(getKey(x4, y4))) {
double w = pow(pow(x2 - x1, 2) + pow(y2 - y1, 2), 0.5);
double l = pow(pow(x3 - x1, 2) + pow(y3 - y1, 2), 0.5);
double area = w * l;
if (ans == 0 || area != 0 && area < ans) {
ans = area;
}
}
}
}
}
return ans;
}
};