Overlap Rectangle
给出两个长方形,判断两个长方形是否重叠
Find if two rectangles overlap Given two rectangles, find if the given two rectangles overlap or not.
Note that a rectangle can be represented by two coordinates, top left and bottom right. So mainly we are given following four coordinates. l1: Top Left coordinate of first rectangle. r1: Bottom Right coordinate of first rectangle. l2: Top Left coordinate of second rectangle. r2: Bottom Right coordinate of second rectangle.
rectanglesOverlap
We need to write a function bool doOverlap(l1, r1, l2, r2) that returns true if the two given rectangles overlap.
One solution is to one by one pick all points of one rectangle and see if the point lies inside the other rectangle or not. This can be done using the algorithm discussed here. Following is a simpler approach. Two rectangles do not overlap if one of the following conditions is true. 1) One rectangle is above top edge of other rectangle. 2) One rectangle is on left side of left edge of other rectangle.
We need to check above cases to find out if given rectangles overlap or not. Following is C++ implementation of the above approach.
code
// Example program
#include <iostream>
#include <string>
using namespace std;
class point {
public:
int x;
int y;
point(int x, int y)
{
this->x = x;
this->y = y;
}
};
bool isOverlap(const point& alt, const point& arb, const point& blt, const point& brb)
{
if(arb.x < blt.x || brb.x < alt.x)
{
return false;
}
if(arb.y > blt.y || brb.y > alt.y)
{
return false;
}
return true;
}
int main()
{
point alt(1, 10);
point arb(3, 8);
point blt(2, 9);
point brb(10, 0);
cout<<isOverlap(alt, arb, blt, brb)<<endl;
return 1;
}