Nik*_*bak 79
这很简单.首先计算交点的坐标,也是一个矩形.
left = max(r1.left, r2.left)
right = min(r1.right, r2.right)
bottom = max(r1.bottom, r2.bottom)
top = min(r1.top, r2.top)
Run Code Online (Sandbox Code Playgroud)
然后,如果交集不为空(left < right && bottom < top),则从两个矩形的公共区域中减去它:r1.area + r2.area - intersection.area.
PS:
bottom = min(r1.bottom, r2.bottom)
top = max(r1.top, r2.top)
Vik*_*ngh 12
以下是使用Java的此算法的完整解决方案:
public static int solution(int K, int L, int M, int N, int P, int Q, int R,
int S) {
int left = Math.max(K, P);
int right = Math.min(M, R);
int bottom = Math.max(L, Q);
int top = Math.min(N, S);
if (left < right && bottom < top) {
int interSection = (right - left) * (top - bottom);
int unionArea = ((M - K) * (N - L)) + ((R - P) * (S - Q))
- interSection;
return unionArea;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
小智 5
我看到这个问题没有得到解答所以我写了一个小的java程序来试试@VicJordan和@NikitaRybak在之前的答案中谈过的等式.希望这可以帮助.
/**
* This function tries to see how much of the smallest rectangle intersects
* the with the larger one. In this case we call the rectangles a and b and we
* give them both two points x1,y1 and x2, y2.
*
* First we check for the rightmost left coordinate. Then the leftmost right
* coordinate and so on. When we have iLeft,iRight,iTop,iBottom we try to get the
* intersection points lenght's right - left and bottom - top.
* These lenght's we multiply to get the intersection area.
*
* Lastly we return the result of what we get when we add the two areas
* and remove the intersection area.
*
* @param xa1 left x coordinate A
* @param ya1 top y coordinate A
* @param xa2 right x coordinate A
* @param ya2 bottom y coordinate A
* @param xb1 left x coordinate B
* @param yb1 top y coordinate B
* @param xb2 right x coordinate B
* @param yb2 bottom y coordinate B
* @return Total area without the extra intersection area.
*/
public static float mostlyIntersects(float xa1, float ya1, float xa2, float ya2, float xb1, float yb1, float xb2, float yb2) {
float iLeft = Math.max(xa1, xb1);
float iRight = Math.min(xa2, xb2);
float iTop = Math.max(ya1, yb1);
float iBottom = Math.min(ya2, yb2);
float si = Math.max(0, iRight - iLeft) * Math.max(0, iBottom - iTop);
float sa = (xa2 - xa1) * (ya2 - ya1);
float sb = (xb2 - xb1) * (yb2 - yb1);
return sa + sb - si;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
39454 次 |
| 最近记录: |