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:
public class Solution
{
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H)
{
int tempArea = Math.abs((A - C) * (B - D)) + Math.abs((E - G) * (F - H));
if(A >= G || C <= E) // if one rectangle is to the left(right) of the other one
{
return tempArea;
}
else if(B >= H || D <= F) // if one rectangle is above(below) the other one
{
return tempArea;
}
else
{
double edge1 = (Math.abs(A - C) + Math.abs(E - G) - Math.abs(A - E) - Math.abs(C - G))/2;
double edge2 = (Math.abs(D - B) + Math.abs(H - F) - Math.abs(D - H) - Math.abs(B - F))/2;
return tempArea - (int)(edge1 * edge2);
}
}
}
看了 discuss 发现求公共面积想复杂了:
public class Solution
{
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H)
{
int tempArea = (C - A) * (D - B) + (G - E) * (H - F);
if(C <= E || A >= G || B >= H || D <= F)
{
return tempArea; // on overlap area
}
else
{
return tempArea - (Math.max(A, E) - Math.min(C, G)) * (Math.max(B, F) - Math.min(D, H));
}
}
}
公共面积就是中间的面积,只需要确定某方向上是哪两条边在中间就行了。
网友评论