题目
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.
Example:
Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]
Output: True
Note:
1. All the input integers are in the range [-10000, 10000].
2. A valid square has four equal sides with positive length and four equal angles (90-degree angles).
3. Input points have no order.
解题思路
利用已知的两个点 A,B 直接求出来另外两个点 C,D :
A(x1,y1),B(x2,y2)C(x3,y3),D(x4,y4)
1.
AB
是边时,分两种情况:
1.1 正方形逆时针方向是
ABCD
:
1.2 正方形顺时针方向是 ABCD :
2. AB是对角线时,只有一种情况。设正方形逆时针方向是 ADBC :
代码
#include <stdbool.h>
/* p1 = q1 and p2 = q2 or p1 = q2 and p2 = q1 */
bool same_points(int *p1, int *p2, int *q1, int *q2, int shift)
{
return (p1[0] == q1[0] << shift && p2[0] == q2[0] << shift
&& p1[1] == q1[1] << shift && p2[1] == q2[1] << shift)
|| (p1[0] == q2[0] << shift && p2[0] == q1[0] << shift
&& p1[1] == q2[1] << shift && p2[1] == q1[1] << shift);
}
int valid_square(int* p1, int* p2, int* p3, int* p4)
{
int x1 = p1[0];
int y1 = p1[1];
int x2 = p2[0];
int y2 = p2[1];
int points[][2] =
{
{ x1 + y1 - y2, -x1 + x2 + y1 },
{ x2 + y1 - y2, -x1 + x2 + y2 },
{ x1 - y1 + y2, x1 - x2 + y1 },
{ x2 - y1 + y2, x1 - x2 + y2 },
{ x1 + x2 + y1 - y2, -x1 + x2 + y1 + y2 },
{ x1 + x2 - y1 + y2, x1 - x2 + y1 + y2 }
};
return same_points(points[0], points[1], p3, p4, 0)
|| same_points(points[2], points[3], p3, p4, 0)
|| same_points(points[4], points[5], p3, p4, 1);
}
bool validSquare(int* p1, int p1Size, int* p2, int p2Size, int* p3, int p3Size, int* p4, int p4Size)
{
return !(p1[0] == p2[0] && p1[1] == p2[1] ) /* p1 != p2 */
&& valid_square(p1, p2, p3, p4);
}