我们将四个线段作为其端点的一对坐标。我们需要确定这四个线段是否为矩形。
例子:
输入:segment [] = [(4,2),(7,5),(2,4),(4,2),(2,4),(5,7),(5,7),( 7,5)]输出:是给定这些线段,请制作一个长度为3X2的矩形。输入:segment [] = [(7,0),(10,0),(7,0),(7,3),(7,3),(10,2),(10,2),( 10,0)]输出:否这些线段不构成矩形。下图显示了以上示例。
该问题主要是如何检查给定的四个点是否形成正方形的扩展
我们可以通过使用矩形的属性来解决此问题。首先,我们检查线段的唯一端点总数,如果这些点的计数不等于4,则线段无法形成矩形。然后我们检查所有成对的点之间的距离,最多应有3个不同的距离,一个为对角线,两个为边,最后我们将检查这三个距离之间的关系,对于线段以使这些距离为矩形满足勾股关系,因为矩形的边和对角线形成直角三角形。如果它们满足上述条件,则将线段制成的多边形标记为矩形,否则不标记为矩形。
// C++ program to check whether it is possible
// to make a rectangle from 4 segments
#include
using namespace std;
#define N 4
// structure to represent a segment
struct Segment
{
int ax, ay;
int bx, by;
};
// Utility method to return square of distance
// between two points
int getDis(pair a, pair b)
{
return (a.first - b.first)*(a.first - b.first) +
(a.second - b.second)*(a.second - b.second);
}
// method returns true if line Segments make
// a rectangle
bool isPossibleRectangle(Segment segments[])
{
set< pair > st;
// putiing all end points in a set to
// count total unique points
for (int i = 0; i < N; i++)
{
st.insert(make_pair(segments[i].ax, segments[i].ay));
st.insert(make_pair(segments[i].bx, segments[i].by));
}
// If total unique points are not 4, then
// they can't make a rectangle
if (st.size() != 4)
return false;
// dist will store unique 'square of distances'
set dist;
// calculating distance between all pair of
// end points of line segments
for (auto it1=st.begin(); it1!=st.end(); it1++)
for (auto it2=st.begin(); it2!=st.end(); it2++)
if (*it1 != *it2)
dist.insert(getDis(*it1, *it2));
// if total unique distance are more than 3,
// then line segment can't make a rectangle
if (dist.size() > 3)
return false;
// copying distance into array. Note that set maintains
// sorted order.
int distance[3];
int i = 0;
for (auto it = dist.begin(); it != dist.end(); it++)
distance[i++] = *it;
// If line seqments form a square
if (dist.size() == 2)
return (2*distance[0] == distance[1]);
// distance of sides should satisfy pythagorean
// theorem
return (distance[0] + distance[1] == distance[2]);
}
// Driver code to test above methods
int main()
{
Segment segments[] =
{
{4, 2, 7, 5},
{2, 4, 4, 2},
{2, 4, 5, 7},
{5, 7, 7, 5}
};
(isPossibleRectangle(segments))?cout << "Yes\n":cout << "No\n";
}
输出:
Yes