我们给出了四个线段作为它们端点的一对坐标。我们需要判断这四个线段是否构成一个矩形。
例子:
输入:segments[] = [(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)] 输出:不是 这些线段不构成矩形。以上示例如下图所示。
这个问题主要是How to check if given四个点组成一个正方形的扩展
我们可以通过使用矩形的属性来解决这个问题。首先,我们检查线段的唯一端点总数,如果这些点的数量不等于 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
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。