Valid Square问题及解法

问题描述:

Given the coordinates of four points in 2D space, return whether the four points could construct a square.

The coordinate (x,y) of a point is represented by an integer array with two integers.

示例:

Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]
Output: True

问题分析:

判断四个不重复的点是否能构成一个正方形,我们可以从对角线的层面出发,考虑对角线相等且平分,这就确定了四边形是个矩形,在此基础上,相邻的边相等又确定了这个矩形是正方形。


过程详见代码:

class Solution {
public:
    int dis(vector<int> a, vector<int> b)
	{
		return (a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1]);
	}

	bool mid(vector<int> a, vector<int> b, vector<int> c, vector<int> d)
	{
		if (a[0] + b[0] == c[0] + d[0] && a[1] + b[1] == c[1] + d[1]) return true;
		return false;
	} 

	bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) {
		if (p1 == p2 || p1 == p3 || p1 == p4 || p2 == p3 || p2 == p4 || p3 == p4) return false;
		if (dis(p1, p2) == dis(p3, p4) && mid(p1, p2, p3, p4) && dis(p1, p3) == dis(p1, p4)) return true;
		if (dis(p1, p3) == dis(p2, p4) && mid(p1, p3, p2, p4) && dis(p1, p2) == dis(p1, p4)) return true;
		if (dis(p1, p4) == dis(p2, p3) && mid(p1, p4, p2, p3) && dis(p1, p2) == dis(p1, p3)) return true;
		return false;
	}
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值