问:如何判断两个矩形是否重叠?
当满足以下条件时,两个矩形不是重叠的
1.一个矩形在另一个的上面
2.一个矩形在另一个的左边
一个矩形可以被表示为两个点,分别是左上和右下。
我们定义下面四个变量来表示:
1. l1 第一个矩形的左上
2. r1 第一个矩形的右下
3. l2 第二个矩形的左上
4. r2 第二个矩形的右下
所以矩形不重叠的条件是
l1.x > r2.x || l2.x > l1.x // 一个在另一个的左边
l1.y < r2.y || l2.y < r1.y // 一个在另一个的下面
剩下的条件都是重叠
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.
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.
classPoint{intx,y;};// Returns true if two rectangles (l1, r1) and (l2, r2) overlapbool doOverlap(Pointl1,Pointr1,Pointl2,Pointr2){// If one rectangle is on left side of otherif(l1.x >r2.x ||l2.x >r1.x)returnfalse;// If one rectangle is above otherif(l1.y