1. 程式人生 > >計算兩個矩形的重疊面積:Java實現

計算兩個矩形的重疊面積: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));
    }
}