Description
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 <= points.length <= 50
- 0 <= points[i][0] <= 40000
- 0 <= points[i][1] <= 40000
- All points are distinct.
- Answers within 10^-5 of the actual value will be accepted as correct.
分析
题目的意思是:给定很多坐标点,找出能够围成的最小矩形的面积。我参考了一下别人的思路,暴力求解主要是用的直角三角形的向量正交的原理,所以利用三重循环找出两个正交向量,然后再求与该直角三角形构成矩形的第四个点是否在points中。如果满足就更新最小区域面积res就行了。注意所有的点可能都不构成矩形,所以最后要判断一下,res未更改的话,就返回0,否则返回res.
代码
class Solution:
def minAreaFreeRect(self, points: List[List[int]]) -> float:
n=len(points)
pos=[]
res=float('inf')
for i in range(n):
for j in range(i+1,n):
x1=points[j][0]-points[i][0]
y1=points[j][1]-points[i][1]
for k in range(j+1,n):
x2=points[k][0]-points[i][0]
y2=points[k][1]-points[i][1]
x3=points[i][0]+x1+x2
y3=points[i][1]+y1+y2
if([x3,y3] in points and x1*x2+y2*y1==0):
res=min(res,abs(x1*y2-x2*y1))
if(res==float('inf')):
return 0
return res