算法第十六周作业01

xiaoxiao2021-02-28  76

Description

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.

Solution

求解两个矩形的并集的面积,可以转换成两个矩形面积之和减去两个矩形交集的面积求解矩形面积为长乘以宽,其中(对于矩形ABCD)长为C-A,宽为D-B,求解矩形交集的矩形面积时,需要获取交集(可能没有交集)的长宽,要求解长宽,需要获取该矩形的四个边界,其中左边界left为两矩形左边界(A,E)的最大值,右边界right为两矩形右边界(C,G)的最小值,上边界top和下边界bottom同理。

Code

public class Solution { public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { // 获取交集矩形的四个边界 int left = Math.max(A, E); int right = Math.min(C, G); int top = Math.min(D, H); int bottom = Math.max(B, F); // all为两个矩形的面积之和 int all = (D - B) * (C - A) + (H - F) * (G - E); // 如果交集存在,则返回两矩阵之和减交集面积 if(left < right && bottom < top){ return all - (right - left) * (top - bottom); } // 如果没有交集,则返回两个矩形面积之和 return all; } }
转载请注明原文地址: https://www.6miu.com/read-77738.html

最新回复(0)