LeetCode #963. Minimum Area Rectangle II

本文探讨了在二维平面上,由一组给定点形成的任意矩形中,如何找到最小面积的矩形,其边不一定平行于坐标轴。通过具体实例展示了算法的运行过程,包括特殊情况的处理。

题目描述:

Given a set of points in the xy-plane, determine the minimum area of any rectangle formed from these points, with sides not necessarily parallel to the x and y axes.

If there isn't any rectangle, return 0.

Example 1:

Input: [[1,2],[2,1],[1,0],[0,1]]
Output: 2.00000
Explanation: The minimum area rectangle occurs at [1,2],[2,1],[1,0],[0,1], with an area of 2.

Example 2:

Input: [[0,1],[2,1],[1,1],[1,0],[2,0]]
Output: 1.00000
Explanation: The minimum area rectangle occurs at [1,0],[1,1],[2,1],[2,0], with an area of 1.

Example 3:

Input: [[0,3],[1,2],[3,1],[1,3],[2,1]]
Output: 0
Explanation: There is no possible rectangle to form from these points.

Example 4:

Input: [[3,1],[1,1],[0,1],[2,1],[3,3],[3,2],[0,2],[2,3]]
Output: 2.00000
Explanation: The minimum area rectangle occurs at [2,1],[2,3],[3,3],[3,1], with an area of 2.

Note:

  1. 1 <= points.length <= 50
  2. 0 <= points[i][0] <= 40000
  3. 0 <= points[i][1] <= 40000
  4. All points are distinct.
  5. Answers within 10^-5 of the actual value will be accepted as correct.
class Solution {
public:
    double minAreaFreeRect(vector<vector<int>>& points) {
        int n=points.size();
        for(vector<int>& point:points) s.insert(point[0]*N+point[1]);
        
        double area=DBL_MAX;
        for(int i=0;i<n;i++)
        {
            int x1=points[i][0], y1=points[i][1];
            for(int j=i+1;j<n;j++)
            {
                int x2=points[j][0], y2=points[j][1];
                for(int k=j+1;k<n;k++)
                {
                    int x3=points[k][0], y3=points[k][1];
                    helper(x1,y1,x2,y2,x3,y3,area);
                    helper(x2,y2,x1,y1,x3,y3,area);
                    helper(x3,y3,x1,y1,x2,y2,area);
                }
            }
        }
        if(area==DBL_MAX) return 0;
        else return area;
    }
    
    void helper(int& x1, int& y1, int& x2, int& y2, int& x3, int& y3, double& area)
    {   // 确定p1->p2和p1->p3是否组成一个直角,从而可以得到p4
        if((x1-x2)*(x1-x3)+(y1-y2)*(y1-y3)==0)
        {
            int x4=x2+x3-x1, y4=y2+y3-y1;
            if(s.count(x4*N+y4)) 
                area=min(area,get_dist(x1,y1,x2,y2)*get_dist(x1,y1,x3,y3));
        }
    }
    
    double get_dist(int x1, int y1, int x2, int y2)
    {
        return sqrt((double)(x1-x2)*(x1-x2)+(double)(y1-y2)*(y1-y2));
    }

private:
    unordered_set<int> s;
    int N=40001;
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值