# 有效的正方形(593)

# 题目

给定二维空间中四点的坐标,返回四点是否可以构造一个正方形。

一个点的坐标(x,y)由一个有两个整数的整数数组表示。

# 示例

输入: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1] 输出: True

# 注意

  • 所有输入整数都在 [-10000,10000] 范围内。
  • 一个有效的正方形有四个等长的正长和四个等角(90度角)。
  • 输入点没有顺序。

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/valid-square 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

# 算法

一个四边形,他的四条边相等即是个菱形;他的四条边和对角线相等即是个正方形。

我们求出他的四边和对角线的长度(长度均不能为0),然后我们判断其是否有四边相等和两条对角线相等

export const validSquare = (p1, p2, p3, p4) => {
	const getPowLength = (point1, point2) => {
		return Math.pow(point1[0] - point2[0], 2) + Math.pow(point1[1] - point2[1], 2);
	};
	const lines = [
		getPowLength(p1, p2),
		getPowLength(p1, p3),
		getPowLength(p1, p4),
		getPowLength(p2, p3),
		getPowLength(p2, p4),
		getPowLength(p3, p4),
	];
	const borderCount = {};
	for (let i = 0; i < 6; i++) {
		if (lines[i] === 0) return false;
		borderCount[lines[i]] = borderCount[lines[i]] ? borderCount[lines[i]] + 1 : 1;
	}
	if (Object.values(borderCount).toString() === "4,2" || Object.values(borderCount).toString() === "2,4") return true;
	return false;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20