一. 題目描述
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.<喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4NCjxwPjxzdHJvbmc+tv4uIMzixL+31s72PC9zdHJvbmc+PC9wPg0KPHA+zOLEv7Tz0uK63LzytaWjrLy0vMbL47b+zqzGvcPmyc/Bvbj2vtjQzrXEuLK4x8Pmu/2ho8G9vtjQzs2ouf3G5Nfzz8K6zdPSyc+1xNf4seq9+NDQtqjS5aGjvNnJ6Nfcw+a7/bK7u+GzrLn9aW50tcTX7rTz1rWhozwvcD4NCjxwPrj5vt2zo9PDtcS8uLrO1qrKtr/J0tS63L/sveK+9tXiuPbOyszioaO82cnowb249r7Y0M631rHwzqo8Y29kZT5BLCBCPC9jb2RlPqOsPGNvZGU+QXJlYShBICZjdXA7IEIpPC9jb2RlPrHtyr7TycG9uPa+2NDOvNPG8MC0tcS4srjHw+a7/aOs1PLT0NLUz8K5q8q9o7o8Y29kZT5BcmVhKEEgJmN1cDsgQikgPSBBcmVhKEEpICsgQXJlYShCKSAtIEFyZWEoQSAmY2FwOyBCKTwvY29kZT48L3A+DQo8cD48c3Ryb25nPsj9LiDKvsD9tPrC6zwvc3Ryb25nPjwvcD4NCjxwcmUgY2xhc3M9"brush:java;">
// C++ 代碼
class Solution {
public:
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int rectangle1 = (C - A) * (D - B);
int rectangle2 = (G - E) * (H - F);
// 以下是兩個矩陣相交部分的上下左右坐標
int left = max(A, E), right = min(C, G), top = min(D, H), bottom = max(B, F);
if (right <= left || top <= bottom) return rectangle1 + rectangle2;
return rectangle1 + rectangle2 - (right - left) * (top - bottom);
}
};
// Python 代碼
class Solution:
# @param {integer} A
# @param {integer} B
# @param {integer} C
# @param {integer} D
# @param {integer} E
# @param {integer} F
# @param {integer} G
# @param {integer} H
# @return {integer}
def computeArea(self, A, B, C, D, E, F, G, H):
sums = (C - A) * (D - B) + (G - E) * (H - F)
return sums - max(min(C, G) - max(A, E), 0) * max(min(D, H) - max(B, F), 0)
四. 小結
實現算法時,需注意各下標的順序,避免出錯。