題目:
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.
分析:
這是一道數學題,要求計算圖中矩形區域的面積,可以看到圖中區域由兩個矩形組成,那麼目標區域面積的計算需要考慮到兩個矩形的相互位置,若兩個矩形無重合區域,則目標面積爲兩個矩形面積之和;若兩個矩形有重合區域,則目標面積的計算需要用兩個矩形面積減去重合區域面積。在這裏,關鍵是利用四個頂點判斷矩形的相互位置。
代碼:
public class RectangleArea {
public static int computeArea(int A,int B,int C,int D,int E,int F,int G,int H){
int targetArea=0,totalArea=0,togetherArea=0;
totalArea=(C-A)*(D-B)+(G-E)*(H-F);
int A1=Math.max(A, E),B1=Math.max(B, F),C1=Math.min(C, G),D1=Math.min(D, H);
if(C1<A1||D1<B1)
targetArea=totalArea;
else{
togetherArea=(C1-A1)*(D1-B1);
targetArea=totalArea-togetherArea;
}
return targetArea;
}
public static void main(String[] args){
int a=-3,b=0,c=3,d=4,e=0,f=-1,g=9,h=2;
int result=computeArea(a,b,c,d,e,f,g,h);
System.out.println("目標面積:"+result);
}
}