標籤:
Question:
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.
Assume that the total area is never beyond the maximum possible value of int.
Analysis:
問題描述:計算在二維座標系中兩個矩陣覆蓋的面積。每個矩陣由它的左下角和右上方的座標表示。
思路:關鍵是求兩個矩陣的相交部分的面積。有3種情況:一種是無相交的部分;一種是只有橫向和縱向的相交部分,一種是橫向和縱向都有相交部分。然而,由圖形可知,(A,B)的座標一定是小於(C,D),(E,F)的座標一定小於(G,H)。因此看有無相交時,只需要取兩個矩形中左下角中較大的作為新矩形的左下角座標和右上方中較小的作為新矩形的右上方座標,若新的矩形中右上方的座標還要比左下角的座標小,則說明原來的兩個矩形不相交,反之則相交。
PS:在計算矩陣面積的過程中,注意int型座標的計算是否會越界。
Answer:
public class Solution { public static int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { int t1 = Math.max(A, E), t2 = Math.max(B, F), t3 = Math.min(C, G), t4 = Math.min(D, H); int area1 = getArea(A, B, C, D); int area2 = getArea(E, F, G, H); int area3 = getArea(t1, t2, t3, t4); if(t1 > t3 || t2 > t4) return area1 + area2; else return area1 + area2 - area3; } public static int getArea(int A, int B, int C, int D) { int length = 0, wide = 0; double t1 = (double)A * (double)C, t2 = (double)B * (double)D; if(t1 >= 0) length = Math.abs(Math.abs(A) - Math.abs(C)); else length = Math.abs(A) + Math.abs(C); if(t2 >= 0) wide = Math.abs(Math.abs(B) - Math.abs(D)); else wide = Math.abs(B) + Math.abs(D); return length * wide; }}
LeetCode -- Rectangle Area