[LeetCode] Rectangle Area

本文介绍了一种计算两个矩形重叠部分面积的方法。首先判断两矩形是否相交,若相交则计算其重叠部分的边界坐标,最终得出重叠面积。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 }

转载于:https://www.cnblogs.com/jcliBlogger/p/4560825.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值