LeetCode 223. Rectangle Area
Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles.
The first rectangle is defined by its bottom-left corner (ax1, ay1)
and its top-right corner (ax2, ay2)
.
The second rectangle is defined by its bottom-left corner (bx1, by1)
and its top-right corner (bx2, by2)
.
Example 1:
Rectangle Area
Input: ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2
Output: 45
method
要计算覆盖的总面积,需要先计算出重叠部分的面积,再用总面积减去重叠面积
dx<0
的话,一定没有重叠,所以直接返回面积,但是dx>0
也不一定有重叠,还得判断y
方向有没有重叠,如果dy>0
,那就一定有重叠了
int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {
int area = (ax2-ax1) * (ay2-ay1) + (bx2-bx1) * (by2-by1);
int dx = min(ax2, bx2) - max(ax1, bx1);
if (dx < 0) return area; // x方向没有重叠
int dy = min(ay2, by2) - max(ay1, by1);
if (dy < 0) return area; // y方向没有重叠
return area - dx * dy;
}