[LeetCode] Rectangle Area

简介: Well, this problem looks easy at first glance. However, to get a bug-free code may be not that easy. The total square is simply equal to the sum of t...

Well, this problem looks easy at first glance. However, to get a bug-free code may be not that easy.

The total square is simply equal to the sum of the area of the two rectangles minus the area of their overlap. How do we compute the area of a rectangle? Well, simply times its height with its width. And the height and width can be obtained from the coordinates of the corners.

The key to this problem actually lies in how to handle overlap.

First, let's think about when overlap will happen? Well, if one rectangle is completely to the left (or right/top/bottom) of the other, then no overlap will happen; otherwise, it will.

How do we know whether a rectangle is completely to the left of the other? Well, just make sure that the right boundary of it is to the left of the left boundary of the other. That is, C <= E. The right/top/bottom cases can be handled similarly by A >= GD <= FB >= G.

Now we know how to check for overlap. If overlap happens, how do we compute it? The key is to find the boundary of the overlap.

Take the image at the problem statement as an example. It can be seen that the left boundary of the overlap is max(A, E), the right boundary is min(C, G). The top and bottom boundaries aremin(D, H) and max(B, F) similarly. So the area of the overlap is simply (min(C, G) - max(A, E)) * (min(D, H) - max(B, F)).

You should now convince yourself that all kind of overlapping cases can be handled by the above formula by drawing some examples on the paper.

Finally, we have the following code (simply a translation of the above idea).

1 int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
2     int s1 = (C - A) * (D - B); 
3     int s2 = (G - E) * (H - F);
4     if (A >= G || C <= E || D <= F || B >= G)
5         return s1 + s2;  
6     return s1 + s2 - (min(C, G) - max(A, E)) * (min(D, H) - max(B, F));
7 }
目录
相关文章
LeetCode 836. 矩形重叠 Rectangle Overlap
LeetCode 836. 矩形重叠 Rectangle Overlap
LeetCode 836. 矩形重叠 Rectangle Overlap
LeetCode 85. Maximal Rectangle
题意是给定一个二维的零一矩阵,1可以用来围成一些矩阵,题意要求是返回围城矩阵的面积最大值.
83 0
LeetCode 85. Maximal Rectangle
Leetcode-Hard 84. Largest Rectangle in Histogram
Leetcode-Hard 84. Largest Rectangle in Histogram
102 0
Leetcode-Hard 84. Largest Rectangle in Histogram
LeetCode之Construct the Rectangle
LeetCode之Construct the Rectangle
75 0
|
Java
[LeetCode]Max Area of Island 岛屿的最大面积
链接:https://leetcode.com/problems/max-area-of-island/description/难度:Easy题目:695.
872 0
LeetCode 223 Rectangle Area(矩形面积)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50593348 翻译 找到在二维平面中两个相交矩形的总面积。
820 0