在二维平面中,给出了四个点。该算法将检查四个点是否形成正方形。
检查正方形我们必须匹配这些条件-
给定点形成的所有四个边都相同。
所有两个连接侧都是直角的。
Input: Four points {(20, 10), (10, 20), (20, 20), (10, 10)} Output: 点正在形成一个正方形。
isFormingSquare(p1, p2, p3, p4)
在此过程中,我们将使用方法squareDist(p1,p2),它将返回两个给定点的平方距离。
输入: 四点。
输出:给定点形成正方形时为真。
Begin dist12 := squareDist(p1, p2) dist13 := squareDist(p1, p3) dist14 := squareDist(p1, p4) if dist12 = dist13 and 2*dist12 = dist14, then dist := squareDist(p2, p4) return true when dist = squareDist(p3, p4) and dist = dist12 if dist13 = dist14 and 2*dist13 = dist12, then dist := squareDist(p2, p3) return true when dist = squareDist(p2, p4) and dist = dist13 if dist12 = dist14 and 2*dist12 = dist13, then dist := squareDist(p2, p3) return true when dist = squareDist(p3, p4) and dist = dist12 return false End
#include<iostream> using namespace std; struct Point { int x, y; }; int squareDist(Point p, Point q) { return (p.x - q.x)*(p.x - q.x) + (p.y - q.y)*(p.y - q.y); } bool isSquare(Point p1, Point p2, Point p3, Point p4) { //check four points are forming square or not int dist12 = squareDist(p1, p2); // distance from p1 to p2 int dist13 = squareDist(p1, p3); // distance from p1 to p3 int dist14 = squareDist(p1, p4); // distance from p1 to p4 //当p1-p2和p1-p3的长度相同时,(p1-p4)的平方= 2 *(p1-p2) if (dist12 == dist13 && 2*dist12 == dist14) { int dist = squareDist(p2, p4); return (dist == squareDist(p3, p4) && dist == dist12); } //所有其他组合的条件相同 if (dist13 == dist14 && 2*dist13 == dist12) { int dist = squareDist(p2, p3); return (dist == squareDist(p2, p4) && dist == dist13); } if (dist12 == dist14 && 2*dist12 == dist13) { int dist = squareDist(p2, p3); return (dist == squareDist(p3, p4) && dist == dist12); } return false; } int main() { Point p1 = {20, 10}, p2 = {10, 20}, p3 = {20, 20}, p4 = {10, 10}; if(isSquare(p1, p2, p3, p4)) cout << "点正在形成一个正方形。"; else cout << "Points are not forming a square"; }
输出结果
点正在形成一个正方形。