Leetcode 593. 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.
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

AD=BC=ABi=[(x2x1)+(y2y1)i]i=(y1y2)+(x2x1)i

C=x2+y2i+(y1y2)+(x2x1)i=(x2+y1y2,x2x1+y2)

D=x1+y1i+(y1y2)+(x2x1)i=(x1+y1y2,x2x1+y1)

1.2 正方形顺时针方向是 ABCD
AD=BC=AB(i)=[(x2x1)+(y2y1)i]i=(y2y1)+(x1x2)i

C=x2+y2i+(y2y1)+(x1x2)i=(x2+y2y1,x1x2+y2)

D=x1+y1i+(y2y1)+(x1x2)i=(x1+y2y1,x1x2+y1)

2. AB是对角线时,只有一种情况。设正方形逆时针方向是 ADBC
AC=AB12(1+i)=12[(x2x1)+(y2y1)i](1+i)=12[x2x1+y1y2+(x2x1+y2y1)i]

C=x1+y1i+12[x2x1+y1y2+(x2x1+y2y1)i]=12[x1+x2+y1y2+(x2x1+y1+y2)i]

AD=AB12(1i)=12[(x2x1)+(y2y1)i](1i)=12[x2x1+y2y1+(x1x2+y2y1)i]

D=x1+y1i+12[x2x1+y2y1+(x1x2+y2y1)i]=12[x1+x2y1+y2+(x1x2+y1+y2)i]

代码

#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);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值