计算两个矩形的重叠面积:Java实现

一、解决思路

我们分别用p1与p2表示矩形A的左下角和右上角,用p3和p4表示矩形B的左下角和右上角。考虑两个矩形不重叠的情况:

(p1.x > p4.x) || (p2.x < p3.x) || (p1.y > p4.y) || (p2.y < p3.y)

对上述条件取反,即可得到两个矩形重叠的条件。当正向思维比较繁杂时,不妨换种思路,也许会柳暗花明!

二、代码实现

矩形类:Rectangle.java

import java.io.Serializable;

public class Rectangle implements Comparable<Rectangle>, Serializable {
    private double x; //矩形左下角的x坐标
    private double y; //矩形左下角的y坐标
    private double length;
    private double width;

    public Rectangle(double x, double y, double length, double width) {
        this.x = x;
        this.y = y;
        this.length = length;
        this.width = width;
    }

    public double getArea() {
        return length * width;
    }

    public double getX() {
        return x;
    }

    public double getY() {
        return y;
    }

    public double getLength() {
        return length;
    }

    public double getWidth() {
        return width;
    }
    
    @Override
    public int compareTo(Rectangle o) {
        return Double.compare(this.getArea(), o.getArea());
    }
}

计算两个矩形的重叠面积:OverlapAreaOfRectangle.java

public class OverlapAreaOfRectangle {
    public double CalculateOverlapArea(Rectangle rect1, Rectangle rect2) {
        if (rect1 == null || rect2 == null) {
            return -1;
        }
        double p1_x = rect1.getX(), p1_y = rect1.getY();
        double p2_x = p1_x + rect1.getLength(), p2_y = p1_y + rect1.getWidth();
        double p3_x = rect2.getX(), p3_y = rect2.getY();
        double p4_x = p3_x + rect2.getLength(), p4_y = p3_y + rect2.getWidth();

        if (p1_x > p4_x || p2_x < p3_x || p1_y > p4_y || p2_y < p3_y) {
            return 0;
        }
        double Len = Math.min(p2_x, p4_x) - Math.max(p1_x, p3_x);
        double Wid = Math.min(p2_y, p4_y) - Math.max(p1_y, p3_y);
        return Len * Wid;
    }

    public static void main(String[] args) {
        Rectangle rect1 = new Rectangle(0, 1, 3, 2);
        Rectangle rect2 = new Rectangle(2, 0, 2, 2);
        OverlapAreaOfRectangle overlap = new OverlapAreaOfRectangle();
        System.out.println(overlap.CalculateOverlapArea(rect1, rect2));
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值