首页 > 代码库 > [leetcode-593-Valid Square]

[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:
All the input integers are in the range [-10000, 10000].
A valid square has four equal sides with positive length and four equal angles (90-degree angles).
Input points have no order.

思路:

4个点,求出任意两点之间的距离,总共6条线段,存在其中4条相等,而且另外两条也相等就是正方形。

double length(vector<int>& p1, vector<int>& p2)
{  
  int x = abs(p1[0] - p2[0]);
  int y = abs(p1[1] - p2[1]);
  return x*x + y*y;
}
 bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4)
 {
   map<double,int>table;
   table[length(p1,p2)]++;
   table[length(p1,p3)]++;
   table[length(p1,p4)]++;
   table[length(p2,p3)]++;
   table[length(p2,p4)]++;
   table[length(p3,p4)]++;
   if(table.size()!=2) return false;
   
   map<double ,int>::iterator it = table.begin();
   map<double ,int>::iterator temp = it;
   temp++;
   if((it->second ==4 && temp->second ==2 ) ||(it->second ==2 && temp->second ==4) )return true;
   return false;  
}

参考:

http://blog.csdn.net/yuer158462008/article/details/47374545

[leetcode-593-Valid Square]