Rectangle Area

来源:互联网 发布:知乎电子书是什么意思 编辑:程序博客网 时间:2024/05/22 00:50

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.

Credits:
Special thanks to @mithmatt for adding this problem, creating the above image and all test cases.

思路:
分为两种情况,
1)两个矩形不相交,则面积直接相加即可;
2)矩形相交,需要面积直接相加,然后减去相交的阴影部分面积。

那么,问题是:如何判断两个矩形相交?
假设两个矩形,分为是A,B,它们的长宽分别是L(A)、W(A)、L(B)、W(B);
A、B的宽度在Y轴投影距离为Y(情况a:如果A、B的宽度在Y轴投影不相交,在Y>=W(A)+W(B)),
A、B的长度在X轴投影距离为X(情况b:如果A、B的宽度在Y轴投影不相交,在X>=L(A)+L(B)),

如果a,b有一种情况发生,则A、B不相交。

见下图。

这里写图片描述
代码如下:

public class Solution {    public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {        int area1=(D-B)*(C-A);        int area2=(H-F)*(G-E);        int totalWith=(C-A)+(G-E);        int totalHeight=(D-B)+(H-F);        int[] w=findMaxAndMin(new int[]{A,E,C,G});        int maxWidthDis=w[0]-w[1];//在X轴上投影,获得实际宽度        int[] h=findMaxAndMin(new int[]{F,B,H,D});        int maxHeightDis=h[0]-h[1];//在Y轴上投影,获得实际高度        if(maxWidthDis>totalWith||maxHeightDis>totalHeight){//不相交            return area1+area2;        }        return area1+area2-(totalWith-maxWidthDis)*(totalHeight-maxHeightDis);//减去阴影面积    }    //b[0]保存最大值,b[1]保存最小值    private int[] findMaxAndMin(int[] a){        int[] b = new int[2];        b[0]=b[1]=a[0];        for(int i=1;i<a.length;i++){            if(a[i]>b[0]){                b[0]=a[i];            }else if(a[i]<b[1]){                b[1]=a[i];            }        }        return b;    }}
0 0
原创粉丝点击