Find the total area covered by two rectilinear rectangles in a 2D plane.
Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.
Assume that the total area is never beyond the maximum possible value of int.
Solution:
Math: the covered area should be area1 + area2 - intersectionArea.
The key point of this problem becomes to find the 4 intersection points, we can find it by left= Max(A,E), right = Min(C,G), bottom= Max(B,F), up=Min(D,H), and if left>=right or bottom>=up, which means they don't have intersection.Otherwise the area of intersection should be (right-left)*(up-bottom).
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int area1=(C-A)*(D-B);
int area2=(G-E)*(H-F);
int left=Math.max(A,E);
int right=Math.min(C,G);
int up=Math.min(D,H);
int bottom=Math.max(B,F);
int intersection=(right>left && up>bottom)? (right-left)*(up-bottom): 0;
return area1+area2-intersection;
}
No comments:
Post a Comment