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.

 

 

class Solution {
public:
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int leftX = max(A,E);     // x value of the left side of the intersection
        int rightX = min(C,G);   // x value of the right side of the intersection
        int topY = min(H,D);     // y value of the bottom side of the intersection
        int botY = max(F,B);     //y value of the top side of the intersection
        int intersecArea = 0; 
        if(leftX < rightX && topY > botY) //if one of the sides above is misplaced => the intersection is empty
            intersecArea =  (rightX-leftX)*(topY-botY);
        return (C-A)*(D-B) + (G-E)*(H-F) - intersecArea; // Area rectangle 1 + area rectangle 2 - intersection
    }
};

 

posted on 2015-07-09 07:01  风云逸  阅读(69)  评论(0)    收藏  举报