Rectangle Area

Description:

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.

Rectangle Area

Assume that the total area is never beyond the maximum possible value of int.

Code:

 1 int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
 2             Rectangle rect1(A,C,B,D);
 3             Rectangle rect2(E,G,F,H);
 4             
 5             int areaRect1 = (rect1.right-rect1.left)*(rect1.top-rect1.bottom);
 6             int areaRect2 = (rect2.right-rect2.left)*(rect2.top-rect2.bottom);
 7             
 8             int maxLeft = max(rect1.left, rect2.left);
 9             int minRight = min(rect1.right, rect2.right);
10             int maxBottom = max (rect1.bottom, rect2.bottom);
11             int minTop = min(rect1.top, rect2.top);
12             int x = minRight-maxLeft;
13             int y = minTop-maxBottom;
14             if ( x > 0 && y > 0)
15                 return areaRect1+areaRect2-x*y;
16             else
17                 return areaRect1+areaRect2;
18     }
View Code

 

posted @ 2015-06-27 19:53  Rosanne  阅读(241)  评论(0编辑  收藏  举报