Rectangle Area

来源:互联网 发布:c语言有一个函数 编辑:程序博客网 时间:2024/05/20 23:55

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.

这道题碰到了再过一下。

这题不难,其实是要分清楚什么情况下两个矩形会相交就可以了。

首先各自计算出面积,然后如果相交的话再减去相交的部分就可以了。

判断不重合有四个条件:1. a>=h   2. c<= e   3. b >= h   4.d<f。满足这四种情况的话可以直接return结果,否则计算一下重合矩形的4个边界就可以了。

代码:

 

public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {        //计算各自的,然后减去overlap的        int area1 = (D-B) * (C - A);        int area2 = (H-F) * (G-E);        int sum = area1 + area2;        //not overlap        if(C<=E || G<=A)            return sum;        if(B>=H || F >=D)            return sum;        // overlap          int left = Math.max(A, E);        int right = Math.min(C, G);        int top = Math.min(D, H);        int bottom = Math.max(B, F);        return sum - (right - left ) * (top - bottom);    }

0 0