Rectangle Area

本文介绍了一种计算二维平面上两个矩形总面积的方法,包括矩形相交与不相交的情况。提供了详细的判断逻辑及Java代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值